Core\Arr::reduce
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 isU, 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";orangeBuild 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";red=2 blue=1Add 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";3650