array_push() with key value pair

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?


Solution 1:

So what about having:

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

Solution 2:

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

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

Solution 3:

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

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

Solution 4:

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 )