Sometimes you need to process every element in a PHP array and combine the results into a single value. For example, you might want to calculate an order total, multiply numbers, or summarize information from several records.
The array_reduce() function handles these operations using a callback and an accumulator.
What Is array_reduce() in PHP?
The array_reduce() function processes array elements one at a time, combining them into a final result.
Its syntax is:
array_reduce(
array $array,
callable $callback,
mixed $initial = null
): mixed
The parameters are:
$array— The array to process.$callback— A function that combines the current result with each element.$initial— An optional starting value for the calculation.
The callback receives two arguments: $carry, which holds the accumulated result, and $item, which contains the current array value.
The callback's return value becomes the accumulator for the next iteration. After all elements have been processed, PHP returns the final accumulated result.
Example 1: Calculating the Sum of an Array
Let's add several numbers together.
<?php
$numbers = [10, 20, 30, 40];
$total = array_reduce(
$numbers,
fn(int $carry, int $item): int =>
$carry + $item,
0
);
echo $total;
Output:
100
The accumulator begins at zero. PHP adds each number to the previous result:
| Current Value | Accumulated Result |
|---|---|
| 10 | 10 |
| 20 | 30 |
| 30 | 60 |
| 40 | 100 |
The final result is 100. The original array remains unchanged.
Why Is the Initial Value Important?
The third argument determines where the calculation starts.
If you omit it, the accumulator begins as null, not as the first array element. This can lead to unexpected results, especially when multiplying values.
<?php
$numbers = [2, 3, 4];
$product = array_reduce(
$numbers,
fn(int $carry, int $item): int =>
$carry * $item,
1
);
echo $product;
Output:
24
We use 1 because multiplication must start with a value that doesn't change the result.
Common starting values include 0 for addition, 1 for multiplication, an empty string for building text, and an empty array for collecting structured results.
What Happens with an Empty Array?
When the input array is empty, PHP never calls the callback.
Instead, array_reduce() returns the initial value. If no initial value is provided, it returns null.
<?php
$numbers = [];
var_dump(array_reduce(
$numbers,
fn($carry, $item) => $carry + $item,
0
));
var_dump(array_reduce(
$numbers,
fn($carry, $item) => $carry + $item
));
Output:
int(0)
NULL
Providing an appropriate initial value makes the behavior more predictable, particularly when empty arrays are possible.
Example 2: Combining Array Values into Text
The accumulator doesn't have to be a number. You can also use array_reduce() to build strings.
<?php
$words = ["PHP", "is", "useful"];
$sentence = array_reduce(
$words,
fn(string $carry, string $word): string =>
$carry === ""
? $word
: $carry . " " . $word,
""
);
echo $sentence;
Output:
PHP is useful
The callback adds each word to the accumulated string. For simple string joining, implode() is generally a more direct choice.
Practical Example: Calculating an Order Summary
Imagine an online store containing several items in a customer's order. Each item has a price and quantity.
We want to calculate the total number of units and the combined order amount in a single operation.
Create a file named order-summary.php:
<?php
declare(strict_types=1);
$items = [
[
"name" => "Keyboard",
"price" => 50.00,
"quantity" => 2
],
[
"name" => "Mouse",
"price" => 25.00,
"quantity" => 3
],
[
"name" => "Monitor",
"price" => 200.00,
"quantity" => 1
]
];
// Calculate the order summary.
$summary = array_reduce(
$items,
static function (
array $carry,
array $item
): array {
$carry["units"] += $item["quantity"];
$carry["total"] +=
$item["price"] * $item["quantity"];
return $carry;
},
[
"units" => 0,
"total" => 0.0
]
);
// Display the summary.
echo "<h2>Order Summary</h2>";
echo "<p>Total units: "
. $summary["units"]
. "</p>";
echo "<p>Order total: $"
. number_format($summary["total"], 2)
. "</p>";
Browser output:
Order Summary
Total units: 6
Order total: $375.00
The accumulator is an associative array containing two running totals. During each iteration, the callback updates both values and returns the updated array.
This allows one reduction to produce a structured result rather than a single number.
The example uses predefined product data and floating-point prices for simplicity. In production applications, validate quantities and prices, and consider integer cents or decimal arithmetic for financial calculations.
array_reduce() vs Related Functions
| Function | Purpose |
|---|---|
array_reduce() |
Combines array elements into one accumulated result. |
array_map() |
Transforms each element and returns an array. |
array_filter() |
Returns elements that satisfy a condition. |
array_sum() |
Adds numeric array values together. |
Use array_reduce() when you need a custom accumulation operation. For straightforward arithmetic, specialized functions such as array_sum() or array_product() are usually simpler.
Common Mistakes
- Forgetting to return the accumulator: Every callback invocation must return the updated result.
- Using an unsuitable initial value: Starting multiplication at zero produces zero, regardless of the remaining values.
- Expecting array keys in the callback: The callback receives the accumulator and current value, not the element's key.
- Expecting the original array to change: The function returns a result without modifying the input array itself.
- Expecting an early exit: Unlike
array_any(),array_reduce()normally processes every element.
Key Takeaways
array_reduce()combines array elements into one final result.- The callback receives the accumulator first and the current element second.
- The callback must return the updated accumulator.
- The optional initial value determines the starting state.
- An empty array returns the initial value, or
nullif none was provided. - The result can be a number, string, array, or another PHP data type.
The array_reduce() function is useful when several array elements need to contribute to one result. It provides a flexible way to calculate totals, build summaries, and accumulate structured data while keeping the processing logic in one callback.
For additional details, see the official PHP array_reduce() documentation.