A while loop repeats while its condition remains true.

while condition The condition is checked before each loop pass.

While Loops

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

    1<?php2$start→ 3 = 3; //@start=1, 53$current→ 3 = $start3;4$total→ 0 = 0;
  2. $total ← 3, $current ← 2

    pass 1 of 3
    6while ($current3 > 0) {7    $total→ 3 += $current3;8    $current→ 2--;9}
    All 3 passes — pass 1 is the card above
    pass$total$current
    10 33 2
    23 52 1
    35 61 0
  3. echo "start=" . $start . " ";

    11echo "start=" . $start3 . "\n";12echo "total=" . $total6 . "\n";13echo "current=" . $current0 . "\n";
    outputstart=3
    total=6
    current=0
  1. $start ← 1, $current ← 1, $total ← 0

    1<?php2$start→ 1 = 1;3$current→ 1 = $start1;4$total→ 0 = 0;
  2. $total ← 1, $current ← 0

    6while ($current1 > 0) {7    $total→ 1 += $current1;8    $current→ 0--;9}
  3. echo "start=" . $start . " ";

    11echo "start=" . $start1 . "\n";12echo "total=" . $total1 . "\n";13echo "current=" . $current0 . "\n";
    outputstart=1
    total=1
    current=0
  1. $start ← 5, $current ← 5, $total ← 0

    1<?php2$start→ 5 = 5;3$current→ 5 = $start5;4$total→ 0 = 0;
  2. $total ← 5, $current ← 4

    pass 1 of 5
    6while ($current5 > 0) {7    $total→ 5 += $current5;8    $current→ 4--;9}
    All 5 passes — pass 1 is the card above
    pass$total$current
    10 55 4
    25 94 3
    39 123 2
    412 142 1
    514 151 0
  3. 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

  1. $start is 3.
  2. $current begins at 3.
  3. The loop adds $current while it is greater than 0.
  4. Each pass subtracts 1.
  5. The final total is 6 and $current is 0. | 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