Arrays and Iteration
Array Reducing
Reducing combines many array values into one result.
accumulator
An accumulator stores the running result while a loop combines values.
Array Reducing
array_reducing.php
Replay: real traced execution (multi-file project)
<?php
$start = 10;
$total = $start;
foreach ([1, 2, 3, 4] as $value) {
$total = $total + $value;
}
$difference = $total - $start;
echo "start=" . $start . "\n";
echo "total=" . $total . "\n";
echo "difference=" . $difference . "\n";
<?php
$start = 0;
$total = $start;
foreach ([1, 2, 3, 4] as $value) {
$total = $total + $value;
}
$difference = $total - $start;
echo "start=" . $start . "\n";
echo "total=" . $total . "\n";
echo "difference=" . $difference . "\n";
<?php
$start = 20;
$total = $start;
foreach ([1, 2, 3, 4] as $value) {
$total = $total + $value;
}
$difference = $total - $start;
echo "start=" . $start . "\n";
echo "total=" . $total . "\n";
echo "difference=" . $difference . "\n";
$start ← 10, $total ← 10
1<?php2$start→ 10 = 10; //@start=0, 203$total→ 10 = $start10;$total ← 11
pass 1 of 45foreach ([1, 2, 3, 4] as $value1) {6 $total→ 11 = $total + $value1;7}All 4 passes — pass 1 is the card above pass $value$total1 1 10 → 11 2 2 11 → 13 3 3 13 → 16 4 4 16 → 20 $difference ← 10
9$difference→ 10 = $total20 - $start10;1011echo "start=" . $start10 . "\n";12echo "total=" . $total20 . "\n";13echo "difference=" . $difference10 . "\n";outputstart=10 total=20 difference=10
$start ← 0, $total ← 0
1<?php2$start→ 0 = 0;3$total→ 0 = $start0;$total ← 1
pass 1 of 45foreach ([1, 2, 3, 4] as $value1) {6 $total→ 1 = $total + $value1;7}All 4 passes — pass 1 is the card above pass $value$total1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 $difference ← 10
9$difference→ 10 = $total10 - $start0;1011echo "start=" . $start0 . "\n";12echo "total=" . $total10 . "\n";13echo "difference=" . $difference10 . "\n";outputstart=0 total=10 difference=10
$start ← 20, $total ← 20
1<?php2$start→ 20 = 20;3$total→ 20 = $start20;$total ← 21
pass 1 of 45foreach ([1, 2, 3, 4] as $value1) {6 $total→ 21 = $total + $value1;7}All 4 passes — pass 1 is the card above pass $value$total1 1 20 → 21 2 2 21 → 23 3 3 23 → 26 4 4 26 → 30 $difference ← 10
9$difference→ 10 = $total30 - $start20;1011echo "start=" . $start20 . "\n";12echo "total=" . $total30 . "\n";13echo "difference=" . $difference10 . "\n";outputstart=20 total=30 difference=10
Follow the Accumulator
- Start
totalwith$start. - Visit one value at a time.
- Add each value into
total. - Compare the final total with the starting value.
| Step | Value | Running total when start is
10| | --- | --- | --- | | start | none |10| | 1 |1|11| | 2 |2|13| | 3 |3|16| | 4 |4|20|
Exercise: array_reducing.php
Use a loop accumulator to add values from a starting total and print the difference