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 and finally an optional initial value. In our case, we were forced to pass the initial value 0 because the default null is an invalid type for our function signature of int type.
The callback function has two parameters. The first one is the...