PDA

View Full Version : no array_insert() ?!?!?


beetle
10-16-2002, 07:30 PM
I read through what feels like every array-related function in the PHP manual, but there doesn't seem to be an easy way to insert a value at a specified index, and push the rest foward.... $array = ("red","orange","green","blue","indigo","violet");
array_insert($array, "yellow", 2); // <-- what I would like...

// result for $array
Array
(
[0] = "red"
[1] = "orange"
[2] = "yellow"
[3] = "green"
[4] = "blue"
[5] = "indigo"
[6] = "violet"
)What gives? Did I read to much and scramble my brain, therefore missing it? Or do I need to create my own array_insert() type function??

Spookster
10-16-2002, 08:29 PM
I doubt there is such a function in any language. That is not typically something that is needed. The question I have is why do you need to insert something at a specific index? Why can you just add it to the end?

You can write your own quite easily by splicing the array at the point where you want to put something in and then piece it back together after you insert whatever you want in there.

beetle
10-16-2002, 09:03 PM
Why? Good question, It's not for me. Anyhow, I wrote one...function array_insert($array, $pos, $val) {
$before = array_slice($array, 0, $pos);
$after = array_slice($array, $pos);
$before[] = $val;
foreach ($after as $v)
$before[] = $v;
return $before;
}

SYP}{ER
10-18-2002, 12:27 AM
Also, check out array_push(). Sounds like it might be useful?