1

Rather than having a single callback walk over the whole array (like array_map), I would like to know if there is a function to have an array of callbacks filter a value.

$value = 'foo';

$closures = array(
    function($value) { return $value . 'bar'; }
    function($value) { return $value . 'baz'; }
);

// Something other than a foreach with call_user_func?
// $value = array_callbacks($closures, $value);

// vs
foreach ($closures as $callback)
{
    $value = call_user_func($callback, $value);
}

print $value; // foobarbaz

2 Answers 2

2

What you're describing is called "reduce" or "fold" in functional programming, not "map", since you are trying to process a value through the list of values in order, rather than collecting a list of the results of applying each element to the original value.

The following works:

<?
$value = 'foo';

$closures = array(
    function($value) { return $value . 'bar'; },
    function($value) { return $value . 'baz'; }
);


print array_reduce($closures,
                   function ($value, $callback) { return $callback($value); },
                   $value);
?>

But I agree with the other posters that it might be simpler to use foreach. It is a pain to try to do functional stuff in PHP.

Sign up to request clarification or add additional context in comments.

Comments

2

I think the way you're doing it now is the correct one. As far as I'm aware there's no "reverse array map".

You could create a "wrapper" function around the callbacks that calls each in turn and apply that with array_map, but I don't think you'd get any real benefit from it over the foreach approach.

1 Comment

Foreach is actually clean, simple and does what OP wants. PHP really needs a way to simplify a lot of common tasks, but this task is not one of them. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.