CKTIS / PHP
array_reduce()
Fold values from left to right using a callback that receives the previous accumulator and the next value.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
array_reduce(array $array, callable $callback, mixed $initial = null): mixedFold values from left to right using a callback that receives the previous accumulator and the next value. Each return value becomes the following accumulator. The initial value fixes the empty-input result, which otherwise defaults to null. Array keys are not passed to the callback.
Signature
array_reduce(array $array, callable $callback, mixed $initial = null): mixed
Example output
[17,10]
Examples
<?php
$sum = fn(int $carry, int $value): int => $carry + $value;
echo json_encode([array_reduce([2,5], $sum, 10), array_reduce([], $sum, 10)]);
Result
[17,10]