2

Array_Map applies callback to all elements of a supplied array. I want to know if there is any function that applies an array of callbacks to any mixed variable (or all elements of an array)?

For example, array_map works as:

function array_map( $callback , $array )
{
    foreach( $array as $value )
    {
        $callback( $value );
    }
}

I want a native function that works like:

function multi_callback( $callbacks , $mixed )
{
    foreach( $callbacks as $callback )
    {
        if( is_array( $mixed ) )
        {
            array_map( $callback , $mixed );
        }
        else
        {
            $callback( $mixed );
        }
    }
}
Hamid Sarfraz
  • 1,089
  • 1
  • 14
  • 34

1 Answers1

0

There is no such built-in or standard extension function, likely because it's too close in functionality to array_map. Note that for a scalar value, it can be implemented as a single array_map call:

array_map(function ($f) use($scalar) {
        return call_user_func($f, $scalar);
    }, $callbacks
);

With the advent of arrow functions, it's even shorter:

array_map(fn ($f) => $f($scalar), $callbacks);

multi_callback could be implemented in terms of array_map. One change that should be made for performance is to move the is_array($mixed) branches outside of the loop/array_map callback, as it doesn't change over iterations (moving loop-invariant statements outside of loops is a standard optimization). Also, don't forget those return statements.

function map_all(array $functions, $value) {
    return array_map(fn (callable $f) => $f($value), $functions);
}

function multi_callback(array $callbacks, $mixed) {
    if (is_array($mixed)) {
        return array_map(fn ($value) => map_all($callbacks, $value), $mixed);
    } else {
        return map_all($callbacks, $mixed);
    }
}
outis
  • 75,655
  • 22
  • 151
  • 221