Page 1 of 1
Array_Push() add by key?
Posted: Sat May 08, 2010 11:12 pm
by JakeJ
I've hardly had to do anything with arrays in php that didn't come straight out of MySQL so I'm at a little bit of a loss here.
I have the following array:
Code: Select all
$array = array("buttons" => "button1.png", "links" => "link1.php", "texts" => "text1");
Now what I want do is add more buttons, links and texts to this list while maintaining the key. I know I can add to an array using array_push() but that doesn't let me add by key.
Please let me know. Thanks!
Re: Array_Push() add by key?
Posted: Sun May 09, 2010 1:44 am
by cpetercarter
Re: Array_Push() add by key?
Posted: Sun May 09, 2010 2:24 am
by JakeJ
cpetercarter, thanks for the reply but that's not quite what I was getting at. I don't have an array of those other items, I'm trying to avoid creating a ton of arrays by hand and then merging them. There's got to be a better solution.
Re: Array_Push() add by key?
Posted: Sun May 09, 2010 3:17 am
by Eran
I must be missing something here
Code: Select all
$array = array("buttons" => array("button1.png"), "links" => array("link1.php"), "texts" => array("text1"));
$array['buttons'][] = 'button2.png';
$array['links'][] = 'link2.php';
$array['texts'][] = 'text2';
Re: Array_Push() add by key?
Posted: Sun May 09, 2010 3:44 am
by JakeJ
Ah well! Thank you! I had not even thought of that approach. I'll give it a shot tomorrow since it's a bit late tonight but it certainly makes sense looking at it.
Re: Array_Push() add by key?
Posted: Sun May 09, 2010 12:20 pm
by JakeJ
I got the following error:
Fatal error: [] operator not supported for strings in C:\wamp\www\wow\testarray.php on line 8
Line 8 is: $array['Buttons'][]= 'Button2.png';
Anyone else?
Re: Array_Push() add by key?
Posted: Sun May 09, 2010 12:31 pm
by Weirdan
JakeJ wrote:
Fatal error: [] operator not supported for strings in C:\wamp\www\wow\testarray.php on line 8
This is because originally you had array of strings, while pytrin suggested array of arrays since you can't have two items with the same key in an array.