array_push() with key value pair

PhpArrays

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

So what about having:

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

Solution 2 - Php

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

$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));

Solution 3 - Php

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

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

Solution 4 - Php

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
   )

Solution 5 - Php

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 )

Solution 6 - Php

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 :) .

Solution 7 - Php

Just do that:

$data = [
    "dog" => "cat"
];

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

*In php 7 and higher, array is creating using [], not ()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmisteroView Question on Stackoverflow
Solution 1 - PhpdusoftView Answer on Stackoverflow
Solution 2 - PhpHarijs KrūtainisView Answer on Stackoverflow
Solution 3 - PhprogeriopvlView Answer on Stackoverflow
Solution 4 - PhpDeepak VaishnavView Answer on Stackoverflow
Solution 5 - PhpPrince PatelView Answer on Stackoverflow
Solution 6 - PhpMr-FaizanView Answer on Stackoverflow
Solution 7 - PhpxayerView Answer on Stackoverflow