Be careful, array_splice does not behave like you might expect should you try to pass it an object as the replacement argument. Consider the following:
<?php
class Tree {
var $childNodes
function addChild($offset, $node) {
array_splice($this->childNodes, $offset, 0, $node);
}
}
class Node {
var $stuff
...
}
$tree = new Tree();
echo (count($tree->childNodes)); $newNode = new Node();
$tree->addChild(1, $newNode);
echo(count($tree->childNodes)); ?>
In this case, the array has a number of items added to it equal to the number of attributes in the new Node object and the values thereof I.e, if your Node object has 2 attributes with values "foo" and "bar", count($tree->childNodes) will now return 4, with the items "foo" and "bar" added to it. I'm not sure if this qualifies as a bug, or is just a byproduct of how PHP handles objects.
Here's a workaround for this problem:
function array_insertobj(&$array, $offset, $insert) {
$firstPart = array_slice($array, 0, $offset);
$secondPart = array_slice($array, $offset);
$insertPart = array($insert);
$array = array_merge($firstPart, $insertPart, $secondPart);
}
Note that this function makes no allowances for when $offset equals the first or last index in the array. That's because array_unshift and array_push work just fine in those cases. It's only array_splice that can trip you up. Obviously, this is kinda tailor-made for arrays with numeric keys when you don't really care what said keys are, but i'm sure you could adapt it for associative arrays if you needed it.