Reducing combines many array values into one result.

accumulator An accumulator stores the running result while a loop combines values.

Array Reducing

start
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";
  1. $start ← 10, $total ← 10

    1<?php2$start→ 10 = 10; //@start=0, 203$total→ 10 = $start10;
  2. $total ← 11

    pass 1 of 4
    5foreach ([1, 2, 3, 4] as $value1) {6    $total→ 11 = $total + $value1;7}
    All 4 passes — pass 1 is the card above
    pass$value$total
    1110 11
    2211 13
    3313 16
    4416 20
  3. $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
  1. $start ← 0, $total ← 0

    1<?php2$start→ 0 = 0;3$total→ 0 = $start0;
  2. $total ← 1

    pass 1 of 4
    5foreach ([1, 2, 3, 4] as $value1) {6    $total→ 1 = $total + $value1;7}
    All 4 passes — pass 1 is the card above
    pass$value$total
    110 1
    221 3
    333 6
    446 10
  3. $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
  1. $start ← 20, $total ← 20

    1<?php2$start→ 20 = 20;3$total→ 20 = $start20;
  2. $total ← 21

    pass 1 of 4
    5foreach ([1, 2, 3, 4] as $value1) {6    $total→ 21 = $total + $value1;7}
    All 4 passes — pass 1 is the card above
    pass$value$total
    1120 21
    2221 23
    3323 26
    4426 30
  3. $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

  1. Start total with $start.
  2. Visit one value at a time.
  3. Add each value into total.
  4. 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