array reduce

suggest change

array_reduce() reduces an array to a single value. It walks every item, passing the previous result and the current item into the callback, and uses the callback's return value on the next iteration.

Usage: array_reduce($array, function ($carry, $item) { ... }, $initial)

Sum of array

$result = array_reduce([1, 2, 3, 4, 5], function($carry, $item){
    return $carry + $item;
});

result:15

The largest number in an array

$result = array_reduce([10, 23, 211, 34, 25], function($carry, $item){
        return $item > $carry ? $item : $carry;
});

result: 211

With no initial value, $carry starts as null (compared as 0). This form is wrong for an array of only negative numbers; pass an initial value such as PHP_INT_MIN in that case.

Whether every item is greater than 100

$result = array_reduce([101, 230, 210, 341, 251], function($carry, $item){
        return $carry && $item > 100;
}, true); // initial value must be true

result:true

Whether any item is less than 100

$result = array_reduce([101, 230, 21, 341, 251], function($carry, $item){
        return $carry || $item < 100;
}, false); // initial value must be false

result:true

Join with a separator (implode() takes the separator first: implode($separator, $array))

$result = array_reduce(["hello", "world", "PHP", "language"], function($carry, $item){
        return !$carry ? $item : $carry . "-" . $item ;
});

result:"hello-world-PHP-language"

A small helper that takes the array first:

function implode_method($array, $piece){
    return array_reduce($array, function($carry, $item) use ($piece) {
            return !$carry ? $item : ($carry . $piece . $item);
    });
}

$result = implode_method(["hello", "world", "PHP", "language"], "-");

result:"hello-world-PHP-language"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents