PHP 8 reference · Array Functions
PHP array_reduce() Function
Reduce an array to a single value by passing a running total and each element to a callback.
PHP 8 Since 4.0
Syntax
array_reduce(array $array, callable $callback, mixed $initial = null): mixed
Parameters
| Parameter | Description |
|---|---|
array |
The input array. |
callback |
fn($carry, $item) returns the new running value. |
initial optional |
The starting value; also returned for an empty array. Default: null |
Return value
The final value.
Examples
<?php
$cart = [["price" => 3.5, "qty" => 2], ["price" => 12, "qty" => 1]];
echo array_reduce($cart, fn($sum, $line) => $sum + $line["price"] * $line["qty"], 0), "\n";
Output
19
<?php
$words = ["apple", "avocado", "banana"];
$byLetter = array_reduce($words, function ($groups, $word) {
$groups[$word[0]][] = $word;
return $groups;
}, []);
print_r($byLetter);
Output
Array
(
[a] => Array
(
[0] => apple
[1] => avocado
)
[b] => Array
(
[0] => banana
)
)Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
array.reduce()· JavaScript
Related
array_sum()· Return the sum of the values in an array. Numeric strings are converted; an empty array gives 0.array_map()· Apply a callback to every element of one or more arrays and return a new array of the results.array_filter()· Keep only the elements for which a callback returns true. Without a callback it removes empty values; keys are kept.- PHP Array Functions · tutorial
- PHP Arrays · tutorial