php · level 1 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Put an if inside a loop to check every number.
A loop can make a decision on every go. Put an if inside the loop's block, and PHP asks the question again each time round.
% is perfect for this. A number is even when dividing by 2 leaves nothing over, so $house % 2 === 0 is true for 2, 4 and 6.
To count the matches, keep a . Start it at 0 before the loop, then add one inside the if. After the loop, the tally holds the total.
<?php
$left = 0;
for ($house = 1; $house <= 6; $house++) {
if ($house % 2 === 0) {
$left++;
}
}
echo "Letters for the left side: $left\n"; Notice the two closing } marks: the first ends the if, the second ends the loop.
guess first
Which numbers fizz? Make a guess.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
for ($number = 1; $number <= 6; $number++) {
if ($number % 3 === 0) {
echo "Fizz $number\n";
}
}
your turn
Your turn. Hunt for a times table.
Pick how far to count in the first blank, then a times table to spot in the second, like 5. Run it to tally how many you find.
fix it
Tickets 5 and 10 both win, so the tally should be 2. Fix it.
- Follow
$winnersround the loop. What happens to it at the start of every go? - Line 3 sets the tally back to 0 each time round, so only the last win is left.
- Move
$winners = 0;above theforline, so it runs once, then press run.
nailed it
your loops can make decisions. :D
- An
ifinside a loop checks every go. % 2 === 0spots even numbers.- Start a tally at 0 before the loop, not inside it.
new words in your collection
- tally
This lesson isn’t saved. A free account remembers every lesson you finish.