Current Location: Home> Latest Articles> PHP array_reduce() Function Explained: Use Callbacks to Reduce Arrays to a Single Value

PHP array_reduce() Function Explained: Use Callbacks to Reduce Arrays to a Single Value

M66 2025-11-06

Introduction to PHP array_reduce() Function

In PHP, the array_reduce() function is a powerful tool for array processing. It allows you to iterate through an array and reduce multiple elements into a single value using a callback function. This article explains how to use array_reduce() and provides practical code examples to help you understand and apply this function effectively.

array_reduce() Function Syntax

mixed array_reduce(array $array, callable $callback[, mixed $initial = NULL])

Parameter explanation:

  • $array: The array to be processed.
  • $callback: A callback function that defines the operation for each iteration. The function takes two parameters: the result from the previous iteration and the current array element.
  • $initial: Optional parameter to set an initial value. If not provided, the first element of the array is used as the initial value in the first iteration.

Example: Sum Array Elements

Suppose we have an array of numbers and want to calculate their sum:

$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
});
echo $sum; // Output: 15

In this example, $carry represents the result from the previous iteration, and $item is the current element. array_reduce() iterates through the array and adds each element to produce the total sum.

Example: Concatenate Array Elements into a String

Besides summing numbers, array_reduce() can also combine array elements into a string:

$strings = ["Hello", "World", "!"];
$concatenatedString = array_reduce($strings, function($carry, $item) {
    return $carry . " " . $item;
});
echo $concatenatedString; // Output: Hello World !

In this case, the callback function gradually concatenates the array elements into a single string.

Example: Multiply Array Elements

array_reduce() can also handle more complex operations, such as calculating the product of array elements:

$numbers = [1, 2, 3, 4, 5];
$product = array_reduce($numbers, function($carry, $item) {
    return $carry * $item;
}, 1);
echo $product; // Output: 120

Here, we specify an initial value of 1 to ensure the multiplication starts correctly.

Summary

  • array_reduce() allows you to reduce array elements to a single value using a callback function.
  • The callback function takes two parameters: the result of the previous iteration and the current element.
  • An optional initial value can be provided to set the starting point for iteration.

Mastering array_reduce() simplifies array processing logic. Whether you want to sum numbers, concatenate strings, or perform complex operations, this function helps make your code cleaner and more efficient.