O'Reilly logo

Functional PHP by Gilles Crettenand

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The fold or reduce function

Folding refers to a process where you reduce a collection to a return value using a combining function. Depending on the language, this operation can have multiple names like fold, reduce, accumulate, aggregate, or compress. As with other functions related to arrays, the PHP version is the array_reduce function.

You may be familiar with the array_sum function, which calculates the sum of all the values in an array. This is, in fact, a fold and can be easily written using the array_reduce function:

<?php

function sum(int $carry, int $i): int
{
    return $carry + $i;
}

$summed = array_reduce([1, 2, 3, 4], 'sum', 0);
/* $summed contains 10 */

Like the array_filter method, the collection comes first; you then pass a callback ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required