0
0
PHPprogramming~5 mins

Array reduce function in PHP

Choose your learning style9 modes available
Introduction

The array reduce function helps you combine all items in an array into a single value. It is like adding or multiplying all numbers together step by step.

When you want to add all numbers in a list to get a total.
When you want to multiply all numbers in a list to get a product.
When you want to join all words in an array into one sentence.
When you want to find the biggest or smallest number in an array.
When you want to count how many times something appears in a list.
Syntax
PHP
<?php
function array_reduce(array $array, callable $callback, mixed $initial = null): mixed
{
    // $array is the list of items
    // $callback is a function that takes two inputs: the current result and the next item
    // $initial is the starting value for the result
}
?>

The callback function must accept two parameters: the accumulator (result so far) and the current item.

The initial value is optional. If not given, the first array element is used as the initial value.

Examples
Adds all numbers starting from 0 to get the total sum.
PHP
<?php
$numbers = [1, 2, 3, 4];
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);
echo $sum; // 10
?>
Joins all words into one string starting from an empty string.
PHP
<?php
$words = ['Hello', ' ', 'World'];
$sentence = array_reduce($words, function($carry, $item) {
    return $carry . $item;
}, '');
echo $sentence; // Hello World
?>
Works with an empty array by returning the initial value.
PHP
<?php
$empty = [];
$result = array_reduce($empty, function($carry, $item) {
    return $carry + $item;
}, 0);
echo $result; // 0
?>
Works with a single element array, multiplying starting from 1.
PHP
<?php
$single = [5];
$product = array_reduce($single, function($carry, $item) {
    return $carry * $item;
}, 1);
echo $product; // 5
?>
Sample Program

This program shows how to use array_reduce to sum numbers, multiply them, find the maximum, and handle an empty array safely.

PHP
<?php
// Create an array of numbers
$numbers = [2, 4, 6, 8];

// Print the original array
echo "Original array: ";
print_r($numbers);

// Use array_reduce to sum all numbers
$sum = array_reduce($numbers, function($accumulator, $currentItem) {
    return $accumulator + $currentItem;
}, 0);

// Print the sum
echo "Sum of numbers: " . $sum . "\n";

// Use array_reduce to find the product of all numbers
$product = array_reduce($numbers, function($accumulator, $currentItem) {
    return $accumulator * $currentItem;
}, 1);

// Print the product
echo "Product of numbers: " . $product . "\n";

// Use array_reduce to find the maximum number
$max = array_reduce($numbers, function($accumulator, $currentItem) {
    return ($currentItem > $accumulator) ? $currentItem : $accumulator;
});

// Print the maximum number
echo "Maximum number: " . $max . "\n";

// Use array_reduce on an empty array with initial value
$emptyArray = [];
$sumEmpty = array_reduce($emptyArray, function($accumulator, $currentItem) {
    return $accumulator + $currentItem;
}, 0);

// Print result for empty array
echo "Sum of empty array: " . $sumEmpty . "\n";
?>
OutputSuccess
Important Notes

Time complexity is O(n) because it processes each item once.

Space complexity is O(1) as it uses a fixed amount of extra memory.

Common mistake: forgetting to provide an initial value can cause unexpected results with empty arrays.

Use array_reduce when you want to combine array items into one value. For simple sums, PHP also has array_sum which is faster.

Summary

array_reduce combines all items in an array into a single value using a callback function.

It works by carrying a result through each step and updating it with the current item.

Always consider providing an initial value to avoid errors with empty arrays.