Voting

: min(four, four)?
(Example: nine)

The Note You're Voting On

rolandfoxx at yahoo dot com
21 years ago
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
//Very truncated
class Tree {
var
$childNodes

function addChild($offset, $node) {
array_splice($this->childNodes, $offset, 0, $node);
//...rest of function
}

}

class
Node {
var
$stuff
...
}

$tree = new Tree();
// ...set 2 nodes using other functions...
echo (count($tree->childNodes)); //Gives 2
$newNode = new Node();
// ...set node attributes here...
$tree->addChild(1, $newNode);
echo(
count($tree->childNodes)); //Expect 3? wrong!
?>

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.

<< Back to user notes page

To Top