Inserting element into array

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
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Inserting element into array

Post by alex.barylski »

I have an array:

Code: Select all

$arr = array('html', 
               array('head', 
                     array('title', null),
                     array('style', null),
                     array('script', null)
                    )
              );
I want to insert a new element into the above, but want control over which index my new element will reside in.

I have tried:

Code: Select all

$arr[1][1] = array('style2', null);
But this overwrites the existing element and I need to just insert not overwrite...I should hilite emphasis on insert so just adding a new element to the array is not the only thing required, but insertion at a particular index.

Anyone know of an array function or technique I can use to accomplish whats desired???

Thanks :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

feyd wrote:hmm, array_splice() ?
I looked into that, but I don't think it will do what I need...

I need to insert and whatever was originally at the desired index would get shifted down one as would all other elements in the array...no removing of elements allowed :(
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it doesn't have to remove any elements, but the indexes would need to be numeric. Note their examples of usage to do array_push() or array_unshift(). The length argument is zero.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

feyd wrote:it doesn't have to remove any elements, but the indexes would need to be numeric. Note their examples of usage to do array_push() or array_unshift(). The length argument is zero.
Sorry, but I'm missing something here...

array_push pushes an element onto the end of an array, but I need random access.

Or are you saying there is an example which shows how to use both functions mentioned to achieve insertion?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I'm talking about the table of mini-examples on the array_splice() page.
Post Reply