0
0
PhpHow-ToBeginner · 3 min read

How to Use array_reduce in PHP: Syntax and Examples

The array_reduce function in PHP applies a callback function to each element of an array, reducing it to a single value. You provide the array, a callback that takes an accumulator and current value, and an optional initial value for the accumulator.
📐

Syntax

The array_reduce function has this syntax:

  • array: The input array to process.
  • callback: A function that takes two parameters: the accumulator and the current array item, and returns the updated accumulator.
  • initial (optional): The starting value for the accumulator. If omitted, it starts as null.
php
mixed array_reduce(array $array, callable $callback, mixed $initial = null)
💻

Example

This example sums all numbers in an array using array_reduce. The callback adds each number to the accumulator, starting from zero.

php
<?php
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);
echo $sum;
?>
Output
15
⚠️

Common Pitfalls

Common mistakes include:

  • Not providing an initial value, which can cause unexpected null starts.
  • Using a callback that does not return the accumulator, breaking the reduction.
  • Confusing the order of parameters in the callback (first is accumulator, second is current item).
php
<?php
// Wrong: callback does not return accumulator
$numbers = [1, 2, 3];
$result = array_reduce($numbers, function($carry, $item) {
    $carry += $item;
    // missing return
});
echo $result; // outputs nothing or null

// Right: always return accumulator
$result = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);
echo $result; // outputs 6
?>
Output
6
📊

Quick Reference

ParameterDescription
arrayThe array to reduce
callbackFunction(accumulator, currentItem) returning updated accumulator
initialOptional start value for accumulator (default null)

Key Takeaways

Use array_reduce to combine array elements into a single value with a custom callback.
Always return the accumulator from your callback function to continue reduction.
Provide an initial value to avoid unexpected null results.
The callback parameters are accumulator first, then current item.
array_reduce is useful for sums, products, concatenations, and other aggregations.