php · level 1 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Ready for launch? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$count = 3;
while ($count > 0) {
echo "$count\n";
$count = $count - 1;
}
echo "Lift off!\n";
your turn
Your turn. Put the kettle on.
How many friends want tea? Type a number from 1 to 8 in place of the blank, then run it to pour a cup for each one.
fix it
This bouncy loop crashes before it starts. Can you fix it?
- Read the error:
Undefined variable $jumps. Where does that box get its first value? - The loop checks
$jumpsstraight away, but nothing has been put in the box yet. - Add
$jumps = 0;on a new line above thewhile, then press run.
nailed it
your loops know when to stop. :D
whilerepeats its block while the condition istrue.- Set the counter before the loop and change it inside.
- A condition that never turns
falsemakes an infinite loop.
new words in your collection
- while
- infinite loop
This lesson isn’t saved. A free account remembers every lesson you finish.