array_reduce
Reduces an array to a single value.
Syntax
array_reduce(array $array, callable $callback, mixed $initial = null): mixedParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The source array. |
| $callback | callable | A function that receives the accumulated value and the next element. |
| $initial | mixed | Optional. The initial accumulated value. |
Return value
mixedThe final value.
Examples
Summing a field:
<?php
$orders = [['total' => 100], ['total' => 250]];
echo array_reduce($orders, fn ($sum, $order) => $sum + $order['total'], 0);Output:
350The longest word:
<?php
$words = ['pear', 'banana', 'fig'];
echo array_reduce($words, fn ($longest, $word) => strlen($word) > strlen($longest) ? $word : $longest, '');Output:
bananaNotes
Always pass an initial value: without it an empty array gives null.
See also
- array_map — Applies a function to every element of an array.
- array_filter — Keeps the array elements that pass a test.
- array_sum — Returns the sum of the values in an array.
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.