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:
<?php
function rsum($v, $w) {
$v + $w;
return $v;
}
function rmul($v, $w) {
$v *= $w;
return $v;
}
$a = array(1,2,3,4,5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", "No data to reduce");
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>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"Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
