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?

1
169
4/14/2018 2:51:21 PM

Accepted Answer

So what about having:

$data['cat']='wagon';
303
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"));

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon