php object and array - php

I'm trying to write to a variable inside an object and I can't find how to do it.
Array
(
[0] => stdClass Object
(
[id] => 3
[rota_name] => Tea and coffee
[rota_owner_name] => 9
[rota_notes] =>
[rota_entry] => {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}
[rota_advance_email_days] =>
[rota_reminder_sent] =>
)
I want to change person 8 to person 9
So I think that I need to get the rota_entry (using foreach) and then use Json_decode to get an array and then something but my brain now hurts :( I and don't know how to reset it back up to put into the database again.
I can find lots that talks about simple JSON decode or simple array parsing but not something to help with this

This code assumes $obj = the first entry in your array you show.
So $obj = Array[0]
$json = json_decode($obj->rota_entry);
$json->rota_entry0->person = 9;
$obj->rota_entry = json_encode($json);
This code changes rota_entry0 person 8 to 9

// Your original array
$array = [
0 => (object) [
'id' => 3,
'rota_name' => 'Tea and coffee',
'rota_owner_name' => 9,
'rota_notes' => '',
'rota_entry' =>' {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}',
'rota_advance_email_days' => '',
'rota_reminder_sent' => '',
]
];
// Create an empty object to replace the rota_entry key in the array
$rotaEntry = (object) [];
// Iterate through the original rota_entry and replace "person"
foreach (json_decode($array[0]->rota_entry) as $key => $value) {
// You can set whatever logic you want here
// For example: if ($key == "rota_entry4") {$value->person = 4;}
// I'm hardcoding "9"
$value->person = 9;
$rotaEntry->$key = $value;
}
// Assign the newly created (and modified) rotaEntry back to the original array
$array[0]->rota_entry = $rotaEntry;

Try this:
$array = (array) $object;
foreach($array as &$value){
$json = json_encode($value['rota_entry']);
$json -> rota_entry0 -> person = 9;
$value['rota_entry'] = json_encode($json);
}
$array = (object) $array;
good luck.

Related

PHP Nested JSON encoding joining arrays [duplicate]

Take a look at this code:
$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
I'm looking for something like this so that:
print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Is there a function to do this? (because array_push won't work this way)
Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.
You'll have to use
$arrayname[indexname] = $value;
Pushing a value into an array automatically creates a numeric key for it.
When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
You can use the union operator (+) to combine arrays and keep the keys of the added array. For example:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);.
There's more info on the usage of the union operator vs array_merge in the documentation at http://php.net/manual/en/function.array-merge.php.
I wonder why the simplest method hasn't been posted yet:
$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
I would like to add my answer to the table and here it is :
//connect to db ...etc
$result_product = /*your mysql query here*/
$array_product = array();
$i = 0;
foreach ($result_product as $row_product)
{
$array_product [$i]["id"]= $row_product->id;
$array_product [$i]["name"]= $row_product->name;
$i++;
}
//you can encode the array to json if you want to send it to an ajax call
$json_product = json_encode($array_product);
echo($json_product);
hope that this will help somebody
Exactly what Pekka said...
Alternatively, you can probably use array_merge like this if you wanted:
array_merge($_GET, array($rule[0] => $rule[1]));
But I'd prefer Pekka's method probably as it is much simpler.
I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.
I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.
Pretty easy & simple really
// Get All Settings
$settings=getGlobalSettings();
// Apply User Theme Choice
$theme_choice = $settings['theme'];
.. etc etc etc ....
function getGlobalSettings(){
$dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
$MySQL = "SELECT * FROM systemSettings";
$result = mysqli_query($dbc, $MySQL);
while($row = mysqli_fetch_array($result))
{
$settings[$row['item']] = $row['value']; // NO NEED FOR PUSH
}
mysqli_close($dbc);
return $settings;
}
So like the other posts explain... In php there is no need to "PUSH" an array when you are using
Key => Value
AND... There is no need to define the array first either.
$array=array();
Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.
I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!
This is the solution that may useful for u
Class Form {
# Declare the input as property
private $Input = [];
# Then push the array to it
public function addTextField($class,$id){
$this->Input ['type'][] = 'text';
$this->Input ['class'][] = $class;
$this->Input ['id'][] = $id;
}
}
$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');
When you dump it. The result like this
array (size=3)
'type' =>
array (size=3)
0 => string 'text' (length=4)
1 => string 'text' (length=4)
2 => string 'text' (length=4)
'class' =>
array (size=3)
0 => string 'myclass1' (length=8)
1 => string 'myclass2' (length=8)
2 => string 'myclass3' (length=8)
'id' =>
array (size=3)
0 => string 'myid1' (length=5)
1 => string 'myid2' (length=5)
2 => string 'myid3' (length=5)
A bit late but if you don't mind a nested array you could take this approach:
$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));
To clarify,
if you output json_encode($main_array) that will look like [{"Key":"10"}]
A bit weird, but this worked for me
$array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
$array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
$array3 = array();
$count = count($array1);
for($x = 0; $x < $count; $x++){
$array3[$array1[$x].$x] = $array2[$x];
}
foreach($array3 as $key => $value){
$output_key = substr($key, 0, -1);
$output_value = $value;
echo $output_key.": ".$output_value."<br>";
}
$arr = array("key1"=>"value1", "key2"=>"value");
print_r($arr);
// prints array['key1'=>"value1", 'key2'=>"value2"]
The simple way:
$GET = array();
$key = 'one=1';
parse_str($key, $GET);
http://php.net/manual/de/function.parse-str.php
Example array_merge()....
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
Array([color] => green,[0] => 2,[1] => 4,[2] => a,[3] => b,[shape] => trapezoid,[4] => 4,)
I wrote a simple function:
function push(&$arr,$new) {
$arr = array_merge($arr,$new);
}
so that I can "upsert" new element easily:
push($my_array, ['a'=>1,'b'=>2])
2023
A lot of answers. Some helpful, others good but awkward. Since you don't need complicated and expensive arithmetic operations, loops etc. for a simple operation like adding an element to an array, here is my collection of One-Liner-Add-To-Array-Functions.
$array = ['a' => 123, 'b' => 456]; // init Array
$array['c'] = 789; // 1.
$array += ['d' => '012']; // 2.
$array = array_merge($array, ['e' => 345]); // 3.
$array = [...$array, 'f' => 678]; // 4.
print_r($array);
// Output:
/*
Array
(
[a] => 123
[b] => 456
[c] => 789
[d] => 012
[e] => 345
[f] => 678
)
*/
In 99,99% i use version 1. ($array['c'] = 789;). But i like version 4. That is the version with the splat operator (https://www.php.net/manual/en/migration56.new-features.php).
array_push($arr, ['key1' => $value1, 'key2' => value2]);
This works just fine.
creates the the key with its value in the array
hi i had same problem i find this solution you should use two arrays then combine them both
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
reference : w3schools
For add to first position with key and value
$newAarray = [newIndexname => newIndexValue] ;
$yourArray = $newAarray + $yourArray ;
There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.
$intial_content = array();
if (true) {
$intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}
array_push($GET, $GET['one']=1);
It works for me.
I usually do this:
$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);

How to add a new key value pair to every object inside an array in php?

My code:
Scenario 1
$newarray = array();
foreach($rows as $k => $v)
{
$newarray[$k] = $v;
$newarray['newitem'] = 'Add this to existing object';
}
echo json_encode($newarray);
I tried this as well:
Scenario 2
$newarray = array();
foreach($rows as $k => $v)
{
$newarray[$k] = $v;
$newarray[$k]['newitem'] = 'Add this to existing object';
}
echo json_encode($newarray);
In scenario 1, key value pair gets added for after 1st object only. It doesn't loop through.
In scenario 2, i get HTTP ERROR 500
What am I doing wrong here ?
Update:
Existing Output:
[{"pid":"123","date":"2016-08-23 08:08:40","post_title":"AHHH"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"wwwwAHHH"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"xxxAHHH"}]
Required Output:
[{"pid":"123","date":"2016-08-23 08:08:40","post_title":"AHHH","newkey":"new value1"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"wwwwAHHH","newkey":"new value2"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"xxxAHHH","newkey":"new value3"}]
You can make an temporary array containing what you want and then add it to the newarray, so create a temporary array, add the new data and the existing data, then add that to your newarray
$newarray = array();
foreach($rows as $k => $v)
{
$t = $v;
$t['newitem'] = 'Add this to existing object';
$newarray[$k] = $t;
}
echo json_encode($newarray);
EDIT:
Now I know what is in $rows is a JSON String this is the way to do what you want. You cannot foreach over a JSON string, you must first convert it to a PHP data structure, then foreach over it adding the new data, then convert it back to a JSON String
$rows = '[{"pid":"123","date":"2016-08-23 08:08:40","post_title":"AHHH"},{"pid":"223","date":"2016-08-‌​23 08:08:40","post_title":"wwwwAHHH"},{"pid":"223","date":"2016‌​-08-23 08:08:40","post_title":"xxxAHHH"}]';
$objArray = json_decode($rows);
$newarray = array();
foreach($objArray as $v)
{
$v->newitem = 'Add this to existing object';
$newarray[] = $v;
}
print_r($newarray);
echo json_encode($newarray);
The $newArray is now
Array
(
[0] => stdClass Object
(
[pid] => 123
[date] => 2016-08-23 08:08:40
[post_title] => AHHH
[newitem] => Add this to existing object
)
[1] => stdClass Object
(
[pid] => 223
[date] => 2016-08-‌​23 08:08:40
[post_title] => wwwwAHHH
[newitem] => Add this to existing object
)
[2] => stdClass Object
(
[pid] => 223
[date] => 2016‌​-08-23 08:08:40
[post_title] => xxxAHHH
[newitem] => Add this to existing object
)
)
And the new JSON String will be
[ {"pid":"123",
"date":"2016-08-23 08:08:40",
"post_title":"AHHH",
"newitem":"Add this to existing object"
},
{"pid":"223",
"date":"2016-08-\u200c\u200b23 08:08:40",
"post_title":"wwwwAHHH",
"newitem":"Add this to existing object"
},
{"pid":"223",
"date":"2016\u200c\u200b-08-23 08:08:40",
"post_title":"xxxAHHH",
"newitem":"Add this to existing object"
}
]
In Scenario 1, you are assigning a different value, $v, to the same array key each time so it is just being overridden (and would eventually end up being the value of the last row passed to the foreach):
$newarray['newitem'] = 'Add this to existing object';
Scenario 2 is on the right lines but needs changing slightly. In Scenario 2 you are adding an array containing $v but then overriding it straight away:
$newarray[$k] = $v;
$newarray[$k]['newitem'] = 'Add this to existing object';
You need to give the items separate keys so a solution could be to use an 'olditem' key to assign the initial value to:
$newarray[$k]['olditem'] = $v;
$newarray[$k]['newitem'] = 'Add this to existing object';
There are many solutions you could do depending on how you want the array to be structured but the key principle is to ensure the values have separate keys so they do not override each other.

PHP Remove Multidimensional Array Value

I have array multidimensional code like this:
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
unset($array[$eaten]);
and what i need is to delete 'grape' from the array because 'grape' already eaten. how to fix my code to unset the 'grape'?
and my question number two, if it can be unset, is there a way to unset multi value like
unset($array,['grape','orange']);
thanks for help..
You can remove eaten element by following way. Use array_search() you can find key at the position of your eaten element.
Here below code shows that in any multidimensional array you can call given function.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
$array = removeElement($array, $eaten);
function removeElement($data_arr, $eaten)
{
foreach($data_arr as $k => $single)
{
if (count($single) != count($single, COUNT_RECURSIVE))
{
$data_arr[$k] = removeElement($single, $eaten);
}
else
{
if(($key = array_search($eaten, $single)) !== false)
{
unset($data_arr[$k][$key]);
}
}
}
return $data_arr;
}
P.S. Please note that you can unset() multiple elements in single call. But the way you are using unset is wrong.
Instead of using unset() i suggest you to create a new Array after removal of required value benefit is that, your original array will remain same, you can use it further:
Example:
// your array
$yourArr = array(
'fruits'=>array('apple','orange','grape', 'pineaple'),
'vegetables'=>array('tomato', 'potato')
);
// remove array that you need
$removeArr = array('grape','tomato');
$newArr = array();
foreach ($yourArr as $key => $value) {
foreach ($value as $finalVal) {
if(!in_array($finalVal, $removeArr)){ // check if available in removal array
$newArr[$key][] = $finalVal;
}
}
}
echo "<pre>";
print_r($newArr);
Result:
Array
(
[fruits] => Array
(
[0] => apple
[1] => orange
[2] => pineaple
)
[vegetables] => Array
(
[0] => potato
)
)
Explanation:
Using this array array('grape','tomato'); which will remove the value that you define in this array.
This is how I would do it.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$unset_item = 'grape';
$array = array_map(function($items) use ($unset_item) {
$found = array_search($unset_item, $items);
if($found){
unset($items[$found]);
}
return $items;
}, $array);

PHP How to push array into array[key]?

This is the code I have:
$orders = Array();
foreach ($unassigned as $uorder) {
$array = Array(
"ordid" => $uorder->idord,
"fecha" => $uorder->datorod,
"cliente" => $uorder->idcli
);
array_push($orders[$uorder->user_id], $array);
}
print_r($orders);
Which results:
Array (
[vendor1] =>
[vendor2] =>
)
I want to make some kind of sort
So I could use $orders[vendor1][0][ordid] to find the first order that the vendor made.
You have to assign $orders[$uorder->user_id] as an array first, otherwise it doesn't make sense to push an item onto it. Additionally, you can use the shorthand append notation:
if(!isset($orders[$uorder->user_id]))
$orders[$uorder->user_id] = array();
$orders[$uorder->user_id][] = $array;
In your foreach loop check if $orders[$uorder->user_id] is an array, if not create one.
foreach($unassigned as $uorder):
if(! is_array($orders[$uorder->user_id]))
$orders[$uorder->user_id] = array();
array_push($orders[$uorder->user_id],Array("ordid" => $uorder->idord, "fecha" => $uorder->datorod, "cliente" => $uorder->idcli));
endforeach;

How to push both value and key into PHP array

Take a look at this code:
$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
I'm looking for something like this so that:
print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Is there a function to do this? (because array_push won't work this way)
Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.
You'll have to use
$arrayname[indexname] = $value;
Pushing a value into an array automatically creates a numeric key for it.
When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
You can use the union operator (+) to combine arrays and keep the keys of the added array. For example:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);.
There's more info on the usage of the union operator vs array_merge in the documentation at http://php.net/manual/en/function.array-merge.php.
I wonder why the simplest method hasn't been posted yet:
$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
I would like to add my answer to the table and here it is :
//connect to db ...etc
$result_product = /*your mysql query here*/
$array_product = array();
$i = 0;
foreach ($result_product as $row_product)
{
$array_product [$i]["id"]= $row_product->id;
$array_product [$i]["name"]= $row_product->name;
$i++;
}
//you can encode the array to json if you want to send it to an ajax call
$json_product = json_encode($array_product);
echo($json_product);
hope that this will help somebody
Exactly what Pekka said...
Alternatively, you can probably use array_merge like this if you wanted:
array_merge($_GET, array($rule[0] => $rule[1]));
But I'd prefer Pekka's method probably as it is much simpler.
I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.
I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.
Pretty easy & simple really
// Get All Settings
$settings=getGlobalSettings();
// Apply User Theme Choice
$theme_choice = $settings['theme'];
.. etc etc etc ....
function getGlobalSettings(){
$dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
$MySQL = "SELECT * FROM systemSettings";
$result = mysqli_query($dbc, $MySQL);
while($row = mysqli_fetch_array($result))
{
$settings[$row['item']] = $row['value']; // NO NEED FOR PUSH
}
mysqli_close($dbc);
return $settings;
}
So like the other posts explain... In php there is no need to "PUSH" an array when you are using
Key => Value
AND... There is no need to define the array first either.
$array=array();
Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.
I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!
This is the solution that may useful for u
Class Form {
# Declare the input as property
private $Input = [];
# Then push the array to it
public function addTextField($class,$id){
$this->Input ['type'][] = 'text';
$this->Input ['class'][] = $class;
$this->Input ['id'][] = $id;
}
}
$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');
When you dump it. The result like this
array (size=3)
'type' =>
array (size=3)
0 => string 'text' (length=4)
1 => string 'text' (length=4)
2 => string 'text' (length=4)
'class' =>
array (size=3)
0 => string 'myclass1' (length=8)
1 => string 'myclass2' (length=8)
2 => string 'myclass3' (length=8)
'id' =>
array (size=3)
0 => string 'myid1' (length=5)
1 => string 'myid2' (length=5)
2 => string 'myid3' (length=5)
A bit late but if you don't mind a nested array you could take this approach:
$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));
To clarify,
if you output json_encode($main_array) that will look like [{"Key":"10"}]
A bit weird, but this worked for me
$array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
$array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
$array3 = array();
$count = count($array1);
for($x = 0; $x < $count; $x++){
$array3[$array1[$x].$x] = $array2[$x];
}
foreach($array3 as $key => $value){
$output_key = substr($key, 0, -1);
$output_value = $value;
echo $output_key.": ".$output_value."<br>";
}
$arr = array("key1"=>"value1", "key2"=>"value");
print_r($arr);
// prints array['key1'=>"value1", 'key2'=>"value2"]
The simple way:
$GET = array();
$key = 'one=1';
parse_str($key, $GET);
http://php.net/manual/de/function.parse-str.php
Example array_merge()....
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
Array([color] => green,[0] => 2,[1] => 4,[2] => a,[3] => b,[shape] => trapezoid,[4] => 4,)
I wrote a simple function:
function push(&$arr,$new) {
$arr = array_merge($arr,$new);
}
so that I can "upsert" new element easily:
push($my_array, ['a'=>1,'b'=>2])
2023
A lot of answers. Some helpful, others good but awkward. Since you don't need complicated and expensive arithmetic operations, loops etc. for a simple operation like adding an element to an array, here is my collection of One-Liner-Add-To-Array-Functions.
$array = ['a' => 123, 'b' => 456]; // init Array
$array['c'] = 789; // 1.
$array += ['d' => '012']; // 2.
$array = array_merge($array, ['e' => 345]); // 3.
$array = [...$array, 'f' => 678]; // 4.
print_r($array);
// Output:
/*
Array
(
[a] => 123
[b] => 456
[c] => 789
[d] => 012
[e] => 345
[f] => 678
)
*/
In 99,99% i use version 1. ($array['c'] = 789;). But i like version 4. That is the version with the splat operator (https://www.php.net/manual/en/migration56.new-features.php).
array_push($arr, ['key1' => $value1, 'key2' => value2]);
This works just fine.
creates the the key with its value in the array
hi i had same problem i find this solution you should use two arrays then combine them both
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
reference : w3schools
For add to first position with key and value
$newAarray = [newIndexname => newIndexValue] ;
$yourArray = $newAarray + $yourArray ;
There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.
$intial_content = array();
if (true) {
$intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}
array_push($GET, $GET['one']=1);
It works for me.
I usually do this:
$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);

Categories