Functional Helpers
Reduce Total
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
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";
$start ← 10, $values ← Array
6$start→ 10 = 10; //@start=0, 207$values→ Array = [2, 3, 4];8$total = array_reduce($valuesArray, "add_total", $start10);function add_total($carry, $value)
pass 1 of 31<?php2function add_total($carry10, $value2) {3 return $carry10 + $value2;4}All 3 passes — pass 1 is the card above pass $carry$value1 10 2 2 12 3 3 15 4 $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
$start ← 0, $values ← Array
6$start→ 0 = 0;7$values→ Array = [2, 3, 4];8$total = array_reduce($valuesArray, "add_total", $start0);function add_total($carry, $value)
pass 1 of 31<?php2function add_total($carry0, $value2) {3 return $carry0 + $value2;4}All 3 passes — pass 1 is the card above pass $carry$value1 0 2 2 2 3 3 5 4 $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
$start ← 20, $values ← Array
6$start→ 20 = 20;7$values→ Array = [2, 3, 4];8$total = array_reduce($valuesArray, "add_total", $start20);function add_total($carry, $value)
pass 1 of 31<?php2function add_total($carry20, $value2) {3 return $carry20 + $value2;4}All 3 passes — pass 1 is the card above pass $carry$value1 20 2 2 22 3 3 25 4 $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