Using array_reduce() with a Callback to Reduce an Array to a Single Value
This article explains PHP's array_reduce() function, describing its parameters, behavior, and how a callback can iteratively process an input array to produce a single result, accompanied by example code demonstrating summation, multiplication, handling of empty arrays, and output inspection.
PHP's array_reduce() function applies a user‑defined callback to each element of an input array, cumulatively reducing the array to a single value.
The function signature is mixed array_reduce (array $input, callable $function [, mixed $initial = NULL]) . The $input parameter is the array to be reduced, $function is the callback that receives the current accumulator and the current array element, and the optional $initial value serves as the initial accumulator (or as the return value when the array is empty).
When called, array_reduce() returns the final accumulator value; if the array is empty and no $initial is provided, it returns NULL .
Example usage:
The above code defines two callbacks: rsum (adds two numbers) and rmul (multiplies them). It then reduces the array $a with each callback, demonstrating the sum (result 15) and the product with an initial value of 10 (result 1200). It also shows how array_reduce() behaves with an empty array, returning the provided initial string.
Output of the var_dump calls is:
array(5) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) }
int(15)
int(1200)
string(17) "No data to reduce"Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.