Control Flow Details
While Loops
A while loop repeats while its condition remains true.
while condition
The condition is checked before each loop pass.
While Loops
while_loop.php
Replay: real traced execution (multi-file project)
<?php
$start = 3;
$current = $start;
$total = 0;
while ($current > 0) {
$total += $current;
$current--;
}
echo "start=" . $start . "\n";
echo "total=" . $total . "\n";
echo "current=" . $current . "\n";
<?php
$start = 1;
$current = $start;
$total = 0;
while ($current > 0) {
$total += $current;
$current--;
}
echo "start=" . $start . "\n";
echo "total=" . $total . "\n";
echo "current=" . $current . "\n";
<?php
$start = 5;
$current = $start;
$total = 0;
while ($current > 0) {
$total += $current;
$current--;
}
echo "start=" . $start . "\n";
echo "total=" . $total . "\n";
echo "current=" . $current . "\n";
$start ← 3, $current ← 3, $total ← 0
1<?php2$start→ 3 = 3; //@start=1, 53$current→ 3 = $start3;4$total→ 0 = 0;$total ← 3, $current ← 2
pass 1 of 36while ($current3 > 0) {7 $total→ 3 += $current3;8 $current→ 2--;9}All 3 passes — pass 1 is the card above pass $total$current1 0 → 3 3 → 2 2 3 → 5 2 → 1 3 5 → 6 1 → 0 echo "start=" . $start . " ";
11echo "start=" . $start3 . "\n";12echo "total=" . $total6 . "\n";13echo "current=" . $current0 . "\n";outputstart=3 total=6 current=0
$start ← 1, $current ← 1, $total ← 0
1<?php2$start→ 1 = 1;3$current→ 1 = $start1;4$total→ 0 = 0;$total ← 1, $current ← 0
6while ($current1 > 0) {7 $total→ 1 += $current1;8 $current→ 0--;9}echo "start=" . $start . " ";
11echo "start=" . $start1 . "\n";12echo "total=" . $total1 . "\n";13echo "current=" . $current0 . "\n";outputstart=1 total=1 current=0
$start ← 5, $current ← 5, $total ← 0
1<?php2$start→ 5 = 5;3$current→ 5 = $start5;4$total→ 0 = 0;$total ← 5, $current ← 4
pass 1 of 56while ($current5 > 0) {7 $total→ 5 += $current5;8 $current→ 4--;9}All 5 passes — pass 1 is the card above pass $total$current1 0 → 5 5 → 4 2 5 → 9 4 → 3 3 9 → 12 3 → 2 4 12 → 14 2 → 1 5 14 → 15 1 → 0 echo "start=" . $start . " ";
11echo "start=" . $start5 . "\n";12echo "total=" . $total15 . "\n";13echo "current=" . $current0 . "\n";outputstart=5 total=15 current=0
Count Down to Zero
$startis3.$currentbegins at3.- The loop adds
$currentwhile it is greater than0. - Each pass subtracts
1. - The final total is
6and$currentis0. | Current before pass | Running total | | --- | --- | |3|3| |2|5| |1|6|
Exercise: while_loop.php
Use a while loop to count down from a start value and print total and current