PHP array_reduce() Function

Quick summary: The PHP array_reduce() function reduces an array to a single value.

PHP array_reduce() Syntax

array_reduce(array $array, callable $callback, mixed $initial = null): mixed
PHP

PHP array_reduce() Basic examples

$nums = [1,2,3];
$sum = array_reduce($nums, fn($c,$n) => $c + $n, 0);
var_dump($sum);
PHP
Output:
int(6)

Aggregates array values.

PHP array_reduce() Real-world usage

$cart = [['price'=>10],['price'=>20]];
$total = array_reduce($cart, fn($c,$i)=>$c+$i['price'], 0);
echo $total;
PHP
Output:
30

Calculates a cart total.

PHP array_reduce() Edge cases

var_dump(array_reduce([], fn($c,$n)=>$c+$n));
PHP
Output:
NULL

Returns null if no initial value is provided.

PHP array_reduce() Common mistakes

Missing initial value

May lead to null results.

Incorrect
array_reduce([], fn($c,$n)=>$c+$n);
Correct
array_reduce([], fn($c,$n)=>$c+$n, 0);

Always provide an initial value.

PHP array_reduce() Frequently Asked Questions

What does array_reduce() do in PHP?

array_reduce() reduces an array to a single value using a callback function.

What is the syntax of array_reduce()?

array_reduce(array $array, callable $callback, mixed $initial = null): mixed

What is the initial value in array_reduce()?

The initial value is the starting value passed to the callback before iteration begins.

Does array_reduce() modify the original array?

No, it processes values and returns a result without modifying the original array.

What happens if the array is empty?

array_reduce() returns the initial value if provided, otherwise null.

What does the callback receive in array_reduce()?

The callback receives the accumulated value and the current array item.

Can array_reduce() return any data type?

Yes, the callback can return any type including arrays or objects.

Is array_reduce() similar to a loop?

Yes, it is a functional alternative to loops for aggregation.

Is array_reduce() fast?

Performance is comparable to loops; readability is often the key factor.

What is a real-world use case of array_reduce()?

Calculating sums, building arrays, or aggregating data into a single result.

Can array_reduce() be used for grouping data?

Yes, it is often used to group or transform datasets.

Can array_reduce() be combined with other array functions?

Yes, it is often combined with array_map() and array_filter().

PHP array_reduce() Related PHP Functions