PHP array_reduce function


The array_reduce() function in PHP is used to iteratively reduce an array to a single value by applying a user-defined callback function to its elements. This function is particularly useful for performing operations like summation, concatenation, or any other kind of aggregation.

Syntax:

array_reduce(array $array, callable $callback, mixed $initial = null): mixed

Parameters:

  • $array: The input array to be reduced.
  • $callback: A callable function that will be applied to each element of the array. This function receives two parameters:
    • The current accumulated value (the result of the previous iteration).
    • The current array element.
  • $initial: (Optional) The initial value to start the reduction. If omitted, the first element of the array will be used as the initial value, and the reduction will start from the second element.

Return Value:

  • Returns the reduced value after processing all elements of the array. If the array is empty and no initial value is provided, it returns null.

Example 1: Summing Values

In this example, we demonstrate how to use array_reduce() to calculate the sum of an array.

<?php $array = [1, 2, 3, 4, 5]; $sum = array_reduce($array, function($carry, $item) { return $carry + $item; }, 0); echo "Sum: " . $sum . "\n"; // Output: Sum: 15 ?>

Output:

Sum: 15

In this case, the callback function adds each element of the array to an accumulated value ($carry), starting from 0. The result is the total sum of the array elements.

Example 2: Concatenating Strings

You can also use array_reduce() to concatenate strings from an array.

<?php $array = ["Hello", " ", "World", "!"]; $concatenated = array_reduce($array, function($carry, $item) { return $carry . $item; }, ""); echo "Concatenated String: " . $concatenated . "\n"; // Output: Concatenated String: Hello World! ?>

Output:

Concatenated String: Hello World!

Here, the callback function concatenates each string element, starting with an empty string.

Example 3: Counting Occurrences

array_reduce() can be used to count the occurrences of values in an array.

<?php $array = ["apple", "banana", "apple", "orange", "banana", "apple"]; $counted = array_reduce($array, function($carry, $item) { if (!isset($carry[$item])) { $carry[$item] = 0; } $carry[$item]++; return $carry; }, []); print_r($counted); ?>

Output:

Array ( [apple] => 3 [banana] => 2 [orange] => 1 )

In this example, the callback function counts how many times each fruit appears in the array, returning an associative array with the counts.

Example 4: Handling an Empty Array

If you call array_reduce() on an empty array without an initial value, it will return null.

<?php $array = []; $result = array_reduce($array, function($carry, $item) { return $carry + $item; }); echo "Result: " . ($result === null ? 'null' : $result) . "\n"; // Output: Result: null ?>

Output:

Result: null

Practical Usage:

  • array_reduce() is useful for:
    • Aggregating data from arrays into a single value.
    • Performing calculations, such as sums or averages.
    • Transforming data structures, such as counting occurrences or combining elements.

Summary:

  • array_reduce($array, $callback, $initial) reduces an array to a single value by applying a callback function to its elements.
  • The function processes each element and returns a final accumulated value.
  • It can handle various operations such as summation, string concatenation, or counting, making it a versatile tool for array manipulation in PHP.