← Back to Chapters

PHP array_reduce()

? PHP array_reduce()

? Quick Overview

The array_reduce() function in PHP reduces an array to a single value by iteratively applying a callback function. Each element is processed and combined into one final result.

? Key Concepts

  • Transforms an array into a single value
  • Uses a callback with accumulator and current value
  • Optional initial accumulator value

? Syntax / Theory

? View Code Example
// Basic syntax of array_reduce()
array_reduce(array $array, callable $callback, mixed $initial = null);

? Example 1: Sum of Numbers

? View Code Example
// Reduce array to sum of all numbers
<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);
echo $sum;
?>

The callback adds each number to the accumulator, resulting in 15.

? Example 2: Maximum Value

? View Code Example
// Reduce array to find maximum value
<?php
$numbers = array(1, 2, 3, 4, 5);
$max = array_reduce($numbers, function($carry, $item) {
    return ($carry > $item) ? $carry : $item;
});
echo $max;
?>

The accumulator keeps the largest number found so far.

✨ Example 3: Concatenate Strings

? View Code Example
// Combine array elements into a sentence
<?php
$words = array("PHP", "is", "awesome");
$result = array_reduce($words, function($carry, $item) {
    return $carry . " " . $item;
});
echo trim($result);
?>

? Interactive Concept

This flow shows how values are accumulated step by step:

? View Pseudo Flow
// Accumulator flow visualization
Start: carry = 0
1 → carry = 1
2 → carry = 3
3 → carry = 6
4 → carry = 10
5 → carry = 15

? Use Cases

  • Summing totals
  • Finding min or max values
  • Combining strings
  • Custom aggregations

✅ Tips & Best Practices

  • Always return the accumulator value
  • Provide an initial value for predictable results
  • Keep callbacks simple and readable

? Try It Yourself

  • Multiply all values in an array
  • Find the longest word using array_reduce()
  • Calculate factorial using reduction