note 103241 added to function.array-walk-recursive

From: Date: Sun, 03 Apr 2011 08:23:21 +0000
Subject: note 103241 added to function.array-walk-recursive
Groups: php.notes 
Request: Send a blank email to php-notes+get-178444@lists.php.net to get a copy of this message
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! ---- Server IP: 69.147.83.197 Probable Submitter: 50.90.215.68 ---- Manual Page -- http://www.php.net/manual/en/function.array-walk-recursive.php Edit -- https://master.php.net/note/edit/103241 Del: integrated -- https://master.php.net/note/delete/103241/integrated Del: useless -- https://master.php.net/note/delete/103241/useless Del: bad code -- https://master.php.net/note/delete/103241/bad+code Del: spam -- https://master.php.net/note/delete/103241/spam Del: non-english -- https://master.php.net/note/delete/103241/non-english Del: in docs -- https://master.php.net/note/delete/103241/in+docs Del: other reasons-- https://master.php.net/note/delete/103241 Reject -- https://master.php.net/note/reject/103241 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#178444) next »