Skip to content
Advertisement

Why is array_walk with anonymous function providing different result than foreach?

PHP Version 5.3.2-1ubuntu4.15

1st, starting values:

$value_array = array('0.000','2.530',8);
$op_value = 2;

Try this:

            foreach($value_array as &$source_value) {
                $source_value = $source_value + $op_value;
            }

And get $value_array == (2,4.53,10);

But if you run this:

            array_walk($value_array,function(&$source_value) {
                $source_value = $source_value + $op_value;
            });

You get $value_array == (0,2.53,8);

The first one gives the expected result, the second one doesn’t. But it does do SOMEthing. The excess 0’s ended up getting chopped off.

Why is this? I wanted to use array_walk but now have to use foreach.

Advertisement

Answer

You can use the use declaration to access the outside variable:

        array_walk($value_array,function(&$source_value) use ($op_value) {
            $source_value = $source_value + $op_value;
        });

or if it’s a global you can do:

        array_walk($value_array,function(&$source_value) {
            global $op_value;
            $source_value = $source_value + $op_value;
        });
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement