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);
}
on June 10th, 2008 at 3:50 am
Could you explain the difference between your code and:
array_splice($array,$position,0,$insert);
}
on June 18th, 2008 at 4:43 am
you rock tenzin - little pieces of clever code, my favourte.
thanks. works like a dream
on July 14th, 2008 at 10:10 am
function array_insert(&$array, $insert, $position) {
array_splice($array,$position,0,array($insert));
}
wrap what you are inserting in the call to array splice in an array that way you can insert complex objects (like arrays). Otherwise the splice method will iterate though the object and individually insert each thing in it.
on July 16th, 2008 at 7:58 am
some offtopic comment:
it's hard to find this page among firefox tabs because desing of favicon is not visually associated with page's design. make a dark favicon.
sorry my english (: