note 106298 added to function.array-walk
| From: | alex_stanhope at hotmail dot com | Date: | Wed, 26 Oct 2011 08:16:35 +0000 |
| Subject: | note 106298 added to function.array-walk | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-184131@lists.php.net to get a copy of this message | ||
I wanted to walk an array and reverse map it into a second array. I decided to use array_walk
because it should be faster than a reset,next loop or foreach(x as &$y) loop.
$output = array();
array_walk($input, 'gmapmark_reverse', $output);
function gmapmark_reverse(&$item, $index, &$target) {
$target[$item['form_key']] = $index;
}
In my debugger I can see that $target is progressively updated, but when array_walk returns, $output
is empty. If however I use a (deprecated) call-by-reference:
array_walk($input, 'gmapmark_reverse', &$output);
$output is returned correctly. Unfortunately there's not an easy way to suppress the warnings:
@array_walk($input, 'gmapmark_reverse', &$output);
doesn't silence them. I've designed a workaround using a static array:
$reverse = array();
array_walk($input, 'gmapmark_reverse');
// call function one last time to get target array out, because parameters don't work
$reverse = gmapmark_reverse($reverse);
function gmapmark_reverse(&$item, $index = 0) {
static $target;
if (!$target) {
$target = array();
}
if (isset($item['form_key'])) {
$target[$item['form_key']] = $index;
}
return($target);
}
----
Server IP: 69.147.83.197
Probable Submitter: 82.71.10.13
----
Manual Page -- http://www.php.net/manual/en/function.array-walk.php
Edit -- https://master.php.net/note/edit/106298
Del: integrated -- https://master.php.net/note/delete/106298/integrated
Del: useless -- https://master.php.net/note/delete/106298/useless
Del: bad code -- https://master.php.net/note/delete/106298/bad+code
Del: spam -- https://master.php.net/note/delete/106298/spam
Del: non-english -- https://master.php.net/note/delete/106298/non-english
Del: in docs -- https://master.php.net/note/delete/106298/in+docs
Del: other reasons-- https://master.php.net/note/delete/106298
Reject -- https://master.php.net/note/reject/106298
Search -- https://master.php.net/manage/user-notes.php