PHP 8.5.0 Alpha 2 available for testing

Voting

: max(one, one)?
(Example: nine)

The Note You're Voting On

alex_stanhope at hotmail dot com
13 years ago
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.

<?php
$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:

<?php
array_walk
($input, 'gmapmark_reverse', &$output);
?>

$output is returned correctly. Unfortunately there's not an easy way to suppress the warnings:

<?php
@array_walk($input, 'gmapmark_reverse', &$output);
?>

doesn't silence them. I've designed a workaround using a static array:

<?php
$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);
}
?>

<< Back to user notes page

To Top