PHP array_reduce() Function
PHP array_reduce() Syntax
array_reduce(array $array, callable $callback, mixed $initial = null): mixed
PHP array_reduce() Basic examples
$nums = [1,2,3];
$sum = array_reduce($nums, fn($c,$n) => $c + $n, 0);
var_dump($sum);
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;
30
Calculates a cart total.
PHP array_reduce() Edge cases
var_dump(array_reduce([], fn($c,$n)=>$c+$n));
NULL
Returns null if no initial value is provided.
PHP array_reduce() Common mistakes
Missing initial value
May lead to null results.
array_reduce([], fn($c,$n)=>$c+$n);
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
-
array_allLearn more about array_all
-
array_anyLearn more about array_any
-
array_change_key_caseLearn more about array_change_key_case
-
array_chunkLearn more about array_chunk
-
array_map PHP examplesLearn more about array_map PHP examples
-
array_filter PHP examplesLearn more about array_filter PHP examples