Foundations
Loops
Loops repeat a block while a counter changes.
for loop
A `for` loop can initialize a counter, test a condition, and update the counter after each pass.
Loops
loops.php
Replay: real traced execution (multi-file project)
<?php
$limit = 4;
$total = 0;
for ($number = 1; $number <= $limit; $number++) {
$total += $number;
}
echo "limit=" . $limit . "\n";
echo "total=" . $total . "\n";
<?php
$limit = 2;
$total = 0;
for ($number = 1; $number <= $limit; $number++) {
$total += $number;
}
echo "limit=" . $limit . "\n";
echo "total=" . $total . "\n";
<?php
$limit = 6;
$total = 0;
for ($number = 1; $number <= $limit; $number++) {
$total += $number;
}
echo "limit=" . $limit . "\n";
echo "total=" . $total . "\n";
$limit ← 4, $total ← 0
1<?php2$limit→ 4 = 4; //@limit=2, 63$total→ 0 = 0;$total ← 1
pass 1 of 45for ($number1 = 1; $number <= $limit4; $number++) {6 $total→ 1 += $number1;7}All 4 passes — pass 1 is the card above pass $number$total1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 echo "limit=" . $limit . " ";
9echo "limit=" . $limit4 . "\n";10echo "total=" . $total10 . "\n";outputlimit=4 total=10
$limit ← 2, $total ← 0
1<?php2$limit→ 2 = 2;3$total→ 0 = 0;$total ← 1
pass 1 of 25for ($number1 = 1; $number <= $limit2; $number++) {6 $total→ 1 += $number1;7}$total ← 3
pass 2 of 25for ($number2 = 1; $number <= $limit2; $number++) {6 $total→ 3 += $number2;7}echo "limit=" . $limit . " ";
9echo "limit=" . $limit2 . "\n";10echo "total=" . $total3 . "\n";outputlimit=2 total=3
$limit ← 6, $total ← 0
1<?php2$limit→ 6 = 6;3$total→ 0 = 0;$total ← 1
pass 1 of 65for ($number1 = 1; $number <= $limit6; $number++) {6 $total→ 1 += $number1;7}All 6 passes — pass 1 is the card above pass $number$total1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 6 6 15 → 21 echo "limit=" . $limit . " ";
9echo "limit=" . $limit6 . "\n";10echo "total=" . $total21 . "\n";outputlimit=6 total=21
Follow the Loop
$limitstarts at4.$totalstarts at0.- The loop adds
1, then2, then3, then4. $totalbecomes10.- The program prints
limit=4andtotal=10. | limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |
Exercise: loops.php
Reproduce total=10 for limit 4, then try limit 2 and 6 and predict each total before running it.