Arrays and Iteration
Foreach Values
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
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";
$bonus ← 1, $total ← 0
1<?php2$bonus→ 1 = 1; //@bonus=0, 33$total→ 0 = 0;$total ← 5
pass 1 of 35foreach ([4, 6, 8] as $score4) {6 $total→ 5 = $total + $score4 + $bonus1;7}All 3 passes — pass 1 is the card above pass $score$total1 4 0 → 5 2 6 5 → 12 3 8 12 → 21 echo "bonus=" . $bonus . " ";
9echo "bonus=" . $bonus1 . "\n";10echo "total=" . $total21 . "\n";outputbonus=1 total=21
$bonus ← 0, $total ← 0
1<?php2$bonus→ 0 = 0;3$total→ 0 = 0;$total ← 4
pass 1 of 35foreach ([4, 6, 8] as $score4) {6 $total→ 4 = $total + $score4 + $bonus0;7}All 3 passes — pass 1 is the card above pass $score$total1 4 0 → 4 2 6 4 → 10 3 8 10 → 18 echo "bonus=" . $bonus . " ";
9echo "bonus=" . $bonus0 . "\n";10echo "total=" . $total18 . "\n";outputbonus=0 total=18
$bonus ← 3, $total ← 0
1<?php2$bonus→ 3 = 3;3$total→ 0 = 0;$total ← 7
pass 1 of 35foreach ([4, 6, 8] as $score4) {6 $total→ 7 = $total + $score4 + $bonus3;7}All 3 passes — pass 1 is the card above pass $score$total1 4 0 → 7 2 6 7 → 16 3 8 16 → 27 echo "bonus=" . $bonus . " ";
9echo "bonus=" . $bonus3 . "\n";10echo "total=" . $total27 . "\n";outputbonus=3 total=27
Add Each Score
- Start
totalat0. foreachvisits4, then6, then8.- Each pass adds the score and
bonus. - The final
totalincludes every visited value. | Score | Added when bonus is1| 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