note 81835 added to function.array-walk-recursive
| From: | JW at osu1 dot php dot net | Date: | Sat, 15 Mar 2008 01:59:09 +0000 |
| Subject: | note 81835 added to function.array-walk-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-137082@lists.php.net to get a copy of this message | ||
This function has a serious bug, which is still not fixed as of the PHP 5.2.5 release. After you
call it, it can accidentally modify your original array. Save yourself hours of frustration by
reading on.
The bug is here: http://bugs.php.net/bug.php?id=42850, and it looks
like it will be fixed for 5.3.
If the array that you walk contains other array elements, they will be turned into references. This
will happen even if the callback function doesn't take its first argument by reference, and
doesn't do anything to the values.
For example, try this:
<?php
$data = array ('key1' => 'val1', 'key2' =>
array('key3' => 'val3'));
function foo($item, $key){}
var_dump($data);
?>
The original array has no references. Now try this:
<?php
array_walk_recursive($data,'foo');
var_dump($data);
?>
Now key2 is a reference, not just an array. So if you do this:
<?php
function test($item){$item['key2'] = array();}
test($data);
var_dump($data);
?>
you will see that test modifies $data, even though it shouldn't.
One workaround is to immediately make a deep copy of the array after calling array_walk_recursive,
like this:
<?php
function array_duplicate($input) {
if (!is_array($input)) return $input;
$output = array();
foreach ($input as $key => $value) {
$output[$key] = array_duplicate($value);
}
return $output;
}
array_walk_recursive($data,'foo');
$data = array_duplicate($data);
var_dump($data);
?>
After doing that, the references are gone.
----
Server IP: 217.160.72.57
Probable Submitter: 69.181.0.49
----
Manual Page -- http://www.php.net/manual/en/function.array-walk-recursive.php
Edit -- https://master.php.net/note/edit/81835
Del: integrated -- https://master.php.net/note/delete/81835/integrated
Del: useless -- https://master.php.net/note/delete/81835/useless
Del: bad code -- https://master.php.net/note/delete/81835/bad+code
Del: spam -- https://master.php.net/note/delete/81835/spam
Del: non-english -- https://master.php.net/note/delete/81835/non-english
Del: in docs -- https://master.php.net/note/delete/81835/in+docs
Del: other reasons-- https://master.php.net/note/delete/81835
Reject -- https://master.php.net/note/reject/81835
Search -- https://master.php.net/manage/user-notes.php