foreach visits each value in an array without manual index arithmetic.

foreach loop A `foreach` loop assigns each array value to a loop variable for one pass through the block.

Foreach Values

bonus
foreach_values.php
Replay: real traced execution (multi-file project)
<?php
$bonus = 1;
$total = 0;

foreach ([4, 6, 8] as $score) {
    $total = $total + $score + $bonus;
}

echo "bonus=" . $bonus . "\n";
echo "total=" . $total . "\n";
<?php
$bonus = 0;
$total = 0;

foreach ([4, 6, 8] as $score) {
    $total = $total + $score + $bonus;
}

echo "bonus=" . $bonus . "\n";
echo "total=" . $total . "\n";
<?php
$bonus = 3;
$total = 0;

foreach ([4, 6, 8] as $score) {
    $total = $total + $score + $bonus;
}

echo "bonus=" . $bonus . "\n";
echo "total=" . $total . "\n";
  1. $bonus ← 1, $total ← 0

    1<?php2$bonus→ 1 = 1; //@bonus=0, 33$total→ 0 = 0;
  2. $total ← 5

    pass 1 of 3
    5foreach ([4, 6, 8] as $score4) {6    $total→ 5 = $total + $score4 + $bonus1;7}
    All 3 passes — pass 1 is the card above
    pass$score$total
    140 → 5
    265 → 12
    3812 → 21
  3. echo "bonus=" . $bonus . " ";

    9echo "bonus=" . $bonus1 . "\n";10echo "total=" . $total21 . "\n";
    outputbonus=1
    total=21
  1. $bonus ← 0, $total ← 0

    1<?php2$bonus→ 0 = 0;3$total→ 0 = 0;
  2. $total ← 4

    pass 1 of 3
    5foreach ([4, 6, 8] as $score4) {6    $total→ 4 = $total + $score4 + $bonus0;7}
    All 3 passes — pass 1 is the card above
    pass$score$total
    140 → 4
    264 → 10
    3810 → 18
  3. echo "bonus=" . $bonus . " ";

    9echo "bonus=" . $bonus0 . "\n";10echo "total=" . $total18 . "\n";
    outputbonus=0
    total=18
  1. $bonus ← 3, $total ← 0

    1<?php2$bonus→ 3 = 3;3$total→ 0 = 0;
  2. $total ← 7

    pass 1 of 3
    5foreach ([4, 6, 8] as $score4) {6    $total→ 7 = $total + $score4 + $bonus3;7}
    All 3 passes — pass 1 is the card above
    pass$score$total
    140 → 7
    267 → 16
    3816 → 27
  3. echo "bonus=" . $bonus . " ";

    9echo "bonus=" . $bonus3 . "\n";10echo "total=" . $total27 . "\n";
    outputbonus=3
    total=27

Add Each Score

  1. Start total at 0.
  2. foreach visits 4, then 6, then 8.
  3. Each pass adds the score and bonus.
  4. The final total includes every visited value. | Score | Added when bonus is 1 | Running total | | --- | --- | --- | | 4 | 5 | 5 | | 6 | 7 | 12 | | 8 | 9 | 21 |

Exercise: foreach_values.php

Use foreach to add each score plus a bonus and print the final total