Backend Development 4 min read

Using array_reduce() in PHP: Syntax, Parameters, and Practical Examples

This article explains PHP's array_reduce() function, detailing its syntax and parameters, and demonstrates its usage through three examples: summing numbers, concatenating strings, and calculating product, helping beginners understand how to reduce arrays to a single value with callbacks.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using array_reduce() in PHP: Syntax, Parameters, and Practical Examples

PHP provides the powerful array_reduce() function to iteratively reduce an array to a single value using a user‑defined callback.

The syntax is mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] ) , where $array is the input array, $callback receives the previous carry value and the current item, and $initial optionally sets the starting value.

Example 1 shows summing numeric elements:

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

Example 2 demonstrates concatenating strings into a single sentence:

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

Example 3 calculates the product of numbers, using an initial value of 1 to avoid a NULL start:

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

In all cases the callback’s first argument ( $carry ) holds the result of the previous iteration, while the second argument ( $item ) is the current array element.

The article concludes that array_reduce() offers a concise and powerful way to process arrays, and beginners should consider it whenever they need to aggregate array data into a single value.

Backend DevelopmentPHPCallbacksarray-manipulationarray_reduce
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.