Definition and Usage
- PHP Version
- 4.0.5
The array_reduce()
function iterates through an array using a callback function to repeatedly reduce its elements into a single value.
Features
- You write the logic to reduce the array elements into a single value inside a callback function.
- At each step, the reduced value is returned using the
return
keyword. - The returned value is then used as the accumulated value in the next iteration, continuing the reduction with the same logic.
- The original array remains unchanged, and the final result is the single value obtained from the repeated reduction.
This function is especially useful when you want to use the elements of an array to produce a single, specific value (or to perform a filtering operation).
Basic Example
The following example demonstrates a useful way to use the array_reduce()
function to sum all elements in a given array into a single value.
/**
* Example of using array_reduce()
* to sum all elements of an array and produce a single accumulated value
*/
// Array to apply array_reduce() on
$array = [1, 2, 3, 4, 5];
// Callback function written by the developer
function sum($total, $number) {
// Add the previous accumulated value and the current element
return $total + $number;
}
// Apply the callback function to all elements and return the single result
$result = array_reduce($array, 'sum');
echo $result; // Output: 15
Syntax
array_reduce(array $array, callable $callback, mixed $initial = null): mixed
Parameters
$array |
The array to which the array_reduce() function will be applied. |
---|---|
$callback |
A callback function that processes each element of the array.
Parameters of the callback function: $callback($carry, $item)
|
$initial |
Optional. The initial accumulated value.
If omitted, the first element of the array is used as the initial accumulated value. |
Return Values
The array_reduce()
function returns the resulting value. If the array is empty and no $initial
value is provided, it returns null
.
How the Callback Function Works
callback(mixed $carry, mixed $item): mixed
array_reduce()
/**
* Callback Function
*
* Can be a named function (user-defined) or an anonymous function
*/
// Using a named function as a callback
function callback($carry, $item) { // define named function
// Logic for accumulating a single value: must return the accumulated result
}
array_reduce($array, 'callback'); // pass the name of the named function as a string
// Using an anonymous function as a callback
array_reduce($array, function($carry, $item) {
// Logic for accumulating a single value: must return the accumulated result
});
The callback function passed to array_reduce()
is the core part that processes array elements and produces a single result.
It is called repeatedly during iteration, storing the previous result in $carry
and providing the current element in $item
.
Below is a detailed explanation of how the callback function operates.
- First iteration: When
array_reduce()
is called, the callback function receives the initial value ($initial
) and the first element of the array.$carry
: assigned the initial value ($initial
).$item
: assigned the value of the first array element.- The callback function is called and returns a new value based on
$carry
and$item
.
- From the second iteration onward: The
$initial
value is no longer used. Instead, the previous iteration's return value ($carry
) and the current element ($item
) are passed to the callback function.$carry
: assigned the value returned from the previous iteration.$item
: assigned the value of the next array element.- The callback function is called and returns a new value based on
$carry
and$item
.
- Iteration continues: This process repeats until all array elements are processed.
- Final result: After processing all elements,
array_reduce()
returns the value returned by the last callback function call as the final result.
In summary, the array_reduce()
function calls the callback function for each element of the array. The callback function returns a new value based on the previous result ($carry
) and the current element ($item
). Repeating this process produces a single final result. This mechanism allows you to use a callback function to aggregate array elements into a single value.
Practical Examples
The array_reduce()
function is commonly used for examples like the ones below.
Summing All Elements of an Array
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, function ($carry, $item) {
return $carry + $item;
});
echo "Sum of all array elements: $sum"; // Output: 'Sum of all array elements: 15'
Multiplying All Elements of an Array
$numbers = [2, 3, 4, 5];
$product = array_reduce($numbers, function ($carry, $item) {
return $carry * $item;
}, 1); // Set the initial accumulated value to 1
echo "Product of all array elements: $product"; // Output: 'Product of all array elements: 120'
In the code above, the initial accumulated value is set to 1, and each element is multiplied to accumulate the result. Using 0 as the initial value would result in all values being multiplied to 0, so setting it to 1 is important.
Finding the Minimum Value in an Array
$numbers = [5, 3, 9, 2, 7];
$min = array_reduce($numbers, function ($carry, $item) {
return ($item < $carry) ? $item : $carry;
}, $numbers[0]);
echo "Minimum value in the array: $min"; // Output: 'Minimum value in the array: 2'
Here, the initial accumulated value is set to the first element of the array ($numbers[0]
), and the callback function selects the current element as the minimum if it is smaller than the accumulated value.
Finding the Maximum Value in an Array
$numbers = [5, 3, 9, 2, 7];
$max = array_reduce($numbers, function ($carry, $item) {
return ($item > $carry) ? $item : $carry;
}, $numbers[0]);
echo "Maximum value in the array: $max"; // Output: 'Maximum value in the array: 9'
Similarly, the initial accumulated value is set to the first array element, and the callback function selects the current element as the maximum if it is greater than the accumulated value.
Concatenating All Array Elements into a String
$words = ['Hello', ' ', 'World', '!'];
$concatenated = array_reduce($words, function ($carry, $item) {
return $carry . $item;
}, '');
echo "Concatenated array elements: $concatenated"; // Output: 'Concatenated array elements: Hello World!'
// Alternatively, you can use the built-in implode() function
$implode = implode('', $words);
echo $implode; // Output: 'Hello World!'
In the code above, the initial accumulated value is set to an empty string (''
). The callback function concatenates the current element to the accumulated value using the dot operator (.
). This results in all array elements being combined into a single string.
For this specific case, using PHP's built-in implode()
function may be more efficient.