Connecting Tech Pros Worldwide Help | Site Map

insert element in middle of array

bugboy's Avatar
Familiar Sight
 
Join Date: Sep 2007
Location: Ontario
Posts: 146
#1: Nov 21 '08
Hi, I have a very long array with sequential numeric keys. What is the best method for inserting an element in the middle thus bumping all following elements along one key.. Like the function array_unshift() but where i can chose where in the key rank to insert the new element.

the best i can come with is to loop through each element after the insert and increment their keys by +1 to make room. I'm hoping there is a function for this that i'm missing...

Thanks!
nathj's Avatar
Expert
 
Join Date: May 2007
Location: North Tyneside
Posts: 854
#2: Nov 21 '08

re: insert element in middle of array


Hi,

What about developing a simple function yourself that increments the key value by 1 where the key value is higher than the inserted value and then calling that function using array_walk().

Alternatively try array_splice() - example 3 is probably the one you want.

Cheers
nathj
bugboy's Avatar
Familiar Sight
 
Join Date: Sep 2007
Location: Ontario
Posts: 146
#3: Nov 21 '08

re: insert element in middle of array


Thanks! It looks like array_splice() is what i'm looking for!

kind regards,
Bugboy
Reply