php · level 1 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A does the same job again and again.
A loop runs the same lines again and again. A for loop is the one to use when you know how many times: run three laps, clap ten times.
Its round brackets hold three parts, split by ;. Where to start, $lap = 1. When to keep going, $lap <= 3. What to do after each go, $lap++, which adds one.
$lap is a : it goes up by one each time round, and you can use it inside the loop. The block in the curly brackets runs once for every go.
<?php
for ($lap = 1; $lap <= 3; $lap++) {
echo "Lap $lap: run!\n";
}
echo "Finished!\n"; $lap++ is a short way to write $lap = $lap + 1.
guess first
Count the steps. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
for ($step = 1; $step < 3; $step++) {
echo "Step $step\n";
}
your turn
Your turn. Give a round of applause.
Choose how many claps, from 1 to 10, and type it in the first blank. Type a cheer for the end in the second, then run it and count along.
fix it
The frog should go Ribbit, then Splash!, three times. Fix it.
- Run it. Splash! only happens once. Which lines are inside the loop's curly brackets?
- Only the lines inside the block repeat. The Splash! line sits after the closing
}. - Move the Splash! line up, above the
}, and indent it, then press run.
nailed it
your code can repeat itself now. :D
- A
forloop repeats its block a set number of times. - Where to start, when to keep going, then
++adds one. - Only lines inside the curly brackets repeat.
new words in your collection
- loop
- for
- counter
This lesson isn’t saved. A free account remembers every lesson you finish.