array_reduce carries one accumulated value across the whole array.

accumulated result A reducer callback receives the current total and the next value.

Reduce Total

start
reduce_total.php
Replay: real traced execution (multi-file project)
<?php
function add_total($carry, $value) {
    return $carry + $value;
}

$start = 10;
$values = [2, 3, 4];
$total = array_reduce($values, "add_total", $start);

echo "start=" . $start . "\n";
echo "total=" . $total . "\n";
<?php
function add_total($carry, $value) {
    return $carry + $value;
}

$start = 0;
$values = [2, 3, 4];
$total = array_reduce($values, "add_total", $start);

echo "start=" . $start . "\n";
echo "total=" . $total . "\n";
<?php
function add_total($carry, $value) {
    return $carry + $value;
}

$start = 20;
$values = [2, 3, 4];
$total = array_reduce($values, "add_total", $start);

echo "start=" . $start . "\n";
echo "total=" . $total . "\n";
  1. $start ← 10, $values ← Array

    6$start→ 10 = 10; //@start=0, 207$values→ Array = [2, 3, 4];8$total = array_reduce($valuesArray, "add_total", $start10);
  2. function add_total($carry, $value)

    pass 1 of 3
    1<?php2function add_total($carry10, $value2) {3    return $carry10 + $value2;4}
    All 3 passes — pass 1 is the card above
    pass$carry$value
    1102
    2123
    3154
  3. $total ← 19

    7$values = [2, 3, 4];8$total→ 19 = array_reduce($valuesArray, "add_total", $start10);910echo "start=" . $start10 . "\n";11echo "total=" . $total19 . "\n";
    outputstart=10
    total=19
  1. $start ← 0, $values ← Array

    6$start→ 0 = 0;7$values→ Array = [2, 3, 4];8$total = array_reduce($valuesArray, "add_total", $start0);
  2. function add_total($carry, $value)

    pass 1 of 3
    1<?php2function add_total($carry0, $value2) {3    return $carry0 + $value2;4}
    All 3 passes — pass 1 is the card above
    pass$carry$value
    102
    223
    354
  3. $total ← 9

    7$values = [2, 3, 4];8$total→ 9 = array_reduce($valuesArray, "add_total", $start0);910echo "start=" . $start0 . "\n";11echo "total=" . $total9 . "\n";
    outputstart=0
    total=9
  1. $start ← 20, $values ← Array

    6$start→ 20 = 20;7$values→ Array = [2, 3, 4];8$total = array_reduce($valuesArray, "add_total", $start20);
  2. function add_total($carry, $value)

    pass 1 of 3
    1<?php2function add_total($carry20, $value2) {3    return $carry20 + $value2;4}
    All 3 passes — pass 1 is the card above
    pass$carry$value
    1202
    2223
    3254
  3. $total ← 29

    7$values = [2, 3, 4];8$total→ 29 = array_reduce($valuesArray, "add_total", $start20);910echo "start=" . $start20 . "\n";11echo "total=" . $total29 . "\n";
    outputstart=20
    total=29