note 103241 deleted from function.array-walk-recursive by danbrown
| From: | danbrown@php.net | Date: | Mon, 04 Apr 2011 14:24:39 +0000 |
| Subject: | note 103241 deleted from function.array-walk-recursive by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178475@lists.php.net to get a copy of this message | ||
Note Submitter: tturner at derossitech dot com
----
I am using php 5.3.3. If you ever need to have your callback function take a third parameter by
reference like so:
function test_array_walk_recursive()
{
$sample = array('dog' => 'woof', 'cat' =>
array('angry' => 'hiss', 'happy' => 'purr'),
'aardvark' => 'kssksskss');
$flattened = array();
array_walk_recursive($sample, array($this, 'walkit'), $flattened);
return($flattened);
}
function walkit($item, $key, &$arr) // receive as reference here
{
array_push($arr, $item);
}
one would expect $flattened to now contain a flat array of values from $sample, however this is NOT
the case. It seems something odd happens because $flattened is passed to array_walk_recursive first
and THEN passed to walkit and walkit does not receive $flattened as an array. In my case it received
it as a string (wtf). It turns out this is because the callback is of the type call_user_func and
this is a known issue with that function also.
To get around it you need to set allow_call_time_pass_reference to 'On' in your php.ini
file, or set it using .htaccess. You may then pass the third parameter by reference, like so:
function test_array_walk_recursive()
{
$sample = array('dog' => 'woof', 'cat' =>
array('angry' => 'hiss', 'happy' => 'purr'),
'aardvark' => 'kssksskss');
$flattened = array();
array_walk_recursive($sample, array($this, 'walkit'), &$flattened); // send as
reference from here
return($flattened);
}
function walkit($item, $key, $arr)
{
array_push($arr, $item);
}
And this now does what is expected since array_walk_recursive is forced to take the parameter by
reference and forward it on. If there is another way to do this without changing
allow_call_time_pass_reference I would love to know how. I hate changing ini files etc!