Search code examples
phpclosuresanonymous-functionarray-walk

array_walk with anonymous function


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.


Solution

  • 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.