note 41118 added to function.array-splice
| From: | rolandfoxxatyahoodotcom at rn2 dot php dot net | Date: | Tue, 30 Mar 2004 17:16:40 +0000 |
| Subject: | note 41118 added to function.array-splice | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-67392@lists.php.net to get a copy of this message | ||
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.
----
Manual Page -- http://www.php.net/manual/en/function.array-splice.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41118
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41118&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41118&report=yes
Search -- http://master.php.net/manage/user-notes.php