Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I have an existing array and I want to add a value to the array.

Normally I would use array_push() to accomplish this but somehow it's not working. Here is my code:

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

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

I don't simply want to add wagon to the array but also the key pussy so I can retrieve the value like so:

echo $data['pussy']; // this will output wagon

Thanks for your help guys, Max

share|improve this question
45  
+1 for the use of "pussy wagon" in an educational context – Nick Mitchell Jun 25 '14 at 8:43
up vote 179 down vote accepted

So what about having:

$data['pussy']='wagon';
share|improve this answer
4  
Thanks, just saved me a headache :) – Phill Pafford Oct 6 '09 at 18:57
1  
Yeah? What's wrong with that. Sounds perfectly normal. :) – Bluebaron Apr 3 '13 at 21:37
    
Dunno if i am tired or stupid... ;) +1 to the answer AND to the question. – taseenb Jun 29 '13 at 4:03
1  
Hehehehe... What a stupid question, I had in my mind. lol – Sami Dec 24 '13 at 14:38
    
What if pussy is in a variable? $pussy = 'pussy'; $data[$pussy] = 'wagon'; Trying this and it gives me an error – Dynelight Oct 5 '14 at 20:26
$data['pussy'] = 'wagon';

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

share|improve this answer

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

$data = array_merge($data, array("pussy"=>"wagon","foo"=>"baar"));
share|improve this answer
    
this does not add any value in array. – Wang'l Pakhrin Nov 22 '15 at 6:19
    
It adds or alters existing keys. RTFM please. – Harijs Krūtainis Nov 30 '15 at 9:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.