Page 1 of 1

Inserting element into array

Posted: Sat Mar 18, 2006 8:27 pm
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 :)

Posted: Sat Mar 18, 2006 8:31 pm
by feyd

Posted: Sat Mar 18, 2006 8:37 pm
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 :(

Posted: Sat Mar 18, 2006 8:43 pm
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.

Posted: Sat Mar 18, 2006 9:24 pm
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?

Posted: Sat Mar 18, 2006 9:30 pm
by feyd
I'm talking about the table of mini-examples on the array_splice() page.