Advertisement
Advertisement


array_push() with key value pair


Question

I have an existing array to which I want to add a value.

I'm trying to achieve that using array_push() to no avail.

Below is my code:

$data = array(
    "dog" => "cat"
);

array_push($data['cat'], 'wagon');

What I want to achieve is to add cat as a key to the $data array with wagon as value so as to access it as in the snippet below:

echo $data['cat']; // the expected output is: wagon

How can I achieve that?

2018/04/14
1
185
4/14/2018 2:51:21 PM

Accepted Answer

So what about having:

$data['cat']='wagon';
2018/04/14
338
4/14/2018 2:52:01 PM

If you need to add multiple key=>value, then try this.

$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
2018/04/14

$data['cat'] = 'wagon';

That's all you need to add the key and value to the array.

2018/04/14

For Example:

$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');

For changing key value:

$data['firstKey'] = 'changedValue'; 
//this will change value of firstKey because firstkey is available in array

output:

Array ( [firstKey] => changedValue [secondKey] => secondValue )

For adding new key value pair:

$data['newKey'] = 'newValue'; 
//this will add new key and value because newKey is not available in array

output:

Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue )

2017/03/01

You don't need to use array_push() function, you can assign new value with new key directly to the array like..

$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);


Output:

   Array(
     [color1] => red
     [color2] => blue
     [color3] => green
   )
2019/10/20

Array['key'] = value;

$data['cat'] = 'wagon';

This is what you need. No need to use array_push() function for this. Some time the problem is very simple and we think in complex way :) .

2020/05/09

Source: https://stackoverflow.com/questions/1355072
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]