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.
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;
        });
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With