Skip to content

Core\Arr::reduce

Core\Arr::reduce(
    array<T> $a,
    callable(U, T, string): U $fn,
    U $initial,
): U

Folds a whole array into one value. A function is called for every entry, and each call receives the value the fold has so far.

You give Core\Arr::reduce an array, a function and a start value. The function receives the value so far, the entry's value and the entry's key, and returns the next value. A function that needs fewer of them declares fewer parameters.

The start value decides the type of the result. A fold that starts from 0 returns a whole number, whatever else happens inside the function, and a fold that builds a text starts from ''. Over an empty array the start value is the result, and the function is not called at all.

Good to know: for a plain total use Core\Arr::sum, which is shorter and faster.

Parameters

  • $aarray<T>The array to reduce.
  • $fncallable(U, T, string): UCalled as ($carry, $value, $key) per entry. It returns the next carry.
  • $initialUThe starting value. Its type is U, which is also the type of the result.

Return value

Returns U. The last carry; $initial itself over an empty array, with no call made.

Examples

Keep the longest word

<?nvs
// Folds an array into one value. The function receives the value the fold has
// so far and the next entry, and returns the value to carry on with.
array<string> $words = ['red', 'orange', 'blue'];
// The fold starts from an empty text, and every longer word replaces it.
string $longest = Core\Arr::reduce($words, fn(string $carry, string $word)
=> Core\Str::length($word) > Core\Str::length($carry) ? $word : $carry, '');
// This prints `orange`.
echo $longest, "\n";
Output
orange

Build one text from an array

<?nvs
// Builds one text out of an array. The start value is a text, so the result is
// a text as well. This function reads the key too.
array<int> $counts = ['red' => 2, 'blue' => 1];
string $line = Core\Arr::reduce($counts, fn(string $carry, int $count, string $colour)
=> $carry . ' ' . $colour . '=' . Core\Str::format('%d', $count), '');
// This prints `red=2 blue=1`.
echo Core\Str::trim($line), "\n";
Output
red=2 blue=1

Add up only the paid orders

<?nvs
// Adds up the amounts of the orders that were paid, in one pass over the list.
// A shop shows this number as the turnover of a day.
array<int> $amounts = ['o-101' => 1250, 'o-102' => 800, 'o-103' => 2400];
array<string> $states = ['o-101' => 'paid', 'o-102' => 'open', 'o-103' => 'paid'];
// The key of the entry is the order number, so the function can look the state
// of that order up.
int $turnover = Core\Arr::reduce($amounts, fn(int $carry, int $cents, string $order)
=> $states[$order] == 'paid' ? $carry + $cents : $carry, 0);
// This prints `3650`.
echo $turnover, "\n";
Output
3650