August 2nd, 2006
PHP: Insert Into an Array at a Specific Position
It's fairly simple to add an element to an array in PHP, but doing just appends the value/element to the last position in the array. You could hack the array_splice function to attempt the, and the format would be like this: array_splice($array, $pos, 0, $newelement); (you could even insert an entire array into the array!). But this function has been created for the sole purpose of inserting into an array, and it's called array_insert().
function array_insert(&$array, $insert, $position = -1) {
$position = ($position == -1) ? (count($array)) : $position ;
if($position != (count($array))) {
$ta = $array;
for($i = $position; $i < (count($array)); $i++) {
if(!isset($array[$i])) {
die(print_r($array, 1)."\r\nInvalid array: All keys must be numerical and in sequence.");
}
$tmp[$i+1] = $array[$i];
unset($ta[$i]);
}
$ta[$position] = $insert;
$array = $ta + $tmp;
//print_r($array);
} else {
$array[$position] = $insert;
}
ksort($array);
return true;
}
$position = ($position == -1) ? (count($array)) : $position ;
if($position != (count($array))) {
$ta = $array;
for($i = $position; $i < (count($array)); $i++) {
if(!isset($array[$i])) {
die(print_r($array, 1)."\r\nInvalid array: All keys must be numerical and in sequence.");
}
$tmp[$i+1] = $array[$i];
unset($ta[$i]);
}
$ta[$position] = $insert;
$array = $ta + $tmp;
//print_r($array);
} else {
$array[$position] = $insert;
}
ksort($array);
return true;
}

on February 8th, 2007 at 9:57 pm
why not
array_splice($array, $position, 0, $insert);
on February 5th, 2008 at 4:47 am
Hi,
Any chance you could comment your function to explain what it is doing internally?
thanks,
on May 19th, 2008 at 6:03 am
function array_insert(&$array, $insert, $position) {
array_splice($array,$position,0,$insert);
}