×

php · level 1 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A loop keeps going while something is true.

A while loop checks a condition, runs its block if the condition is true, then checks again. It keeps going round until the condition turns false.

Set up the counter before the loop and change it inside the block. Here, $knocks++ adds one each time, so the condition is false after the third knock.

Forget to change the counter and the condition stays true for ever. That is an : the program never stops. Always check that something inside the loop moves it towards the end.

<?php
$knocks = 1;
while ($knocks <= 3) {
    echo "Knock $knocks\n";
    $knocks++;
}
echo "Who is there?\n";

If a program seems stuck and the output keeps growing, look for an infinite loop.