Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 643
Buttle Butkus Avatar asked Dec 04 '22 14:12

Buttle Butkus


2 Answers

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;
        });
like image 130
Barmar Avatar answered Dec 21 '22 22:12

Barmar


Alternatively you can also use the third parameter of array_walk to specify an extra parameter to pass to the callback function.

array_walk($value_array, function(&$source_value, $key, $extra_param) { // <--- (2) and use here
    $source_value = $source_value + $extra_param;
}, $op_value); // <--- (1) pass it here
like image 44
DrLightman Avatar answered Dec 22 '22 00:12

DrLightman