Array_Push() add by key?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Array_Push() add by key?

Post 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!
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: Array_Push() add by key?

Post by cpetercarter »

JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Array_Push() add by key?

Post 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.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Array_Push() add by key?

Post 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';
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Array_Push() add by key?

Post 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.
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Array_Push() add by key?

Post 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?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Array_Push() add by key?

Post 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.
Post Reply