2

I am getting familiar with anonymous function and closures in php and I need to use a closure or anon function to pass to array_walk but with an additional parameter here is a simple code block:

        $array = array(1, 2, 3, 4, 5, array(1, 2));

        $callback = function(&$value, $key)
        {
            $value = $key*$value;
        };

        var_dump($array, array_walk_recursive($array, $callback), $array);

It is very simple as it is but say I want to change the function as follows:

        $callback = function(&$value, $key, $multiplier)
        {
            $value = $key*$value*$multiplier;
        };

How can I pass the multiplier to the anon function? Or if it should be a closure how can it be done.

Because as follows is giving me an error:

array_walk_recursive($array, $callback(5))

I know that array_walk has an extra param $user_data which can be passed but I need it with a closure or anon function.

halfer
  • 19,824
  • 17
  • 99
  • 186
Combinu
  • 882
  • 2
  • 10
  • 31

2 Answers2

3

PHP's closures can be used for this:

<?php
$array = array(1, 2, 3, 4, 5, array(1, 2));
$multiplier = 5;

$callback = function(&$value, $key) use ($multiplier) {
    $value = $key*$value*$multiplier;
};

var_dump($array, array_walk_recursive($array, $callback), $array);

Obviously $multiplier can receive non-static values, like ta query argument or the result of a computation. Just make sure to validate and type cast to guarantee a numeric value.

arkascha
  • 41,620
  • 7
  • 58
  • 90
1

You can use two options:

$mltpl = 10;
$callback = function(&$value, $key)
{
    global $mltpl;
    $value = $key*$value*$mltpl;
};

Or

$mltpl = 10;
$callback = function(&$value, $key) use ($mltpl)
{
    $value = $key*$value*$mltpl;
};
u_mulder
  • 54,101
  • 5
  • 48
  • 64