php · level 1 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
is the other path at the fork.
An if on its own either runs its block or skips it. Often you want a plan B. else means otherwise: when the condition is false, PHP runs the block after else instead.
At a fork you always take exactly one path. With if and else, exactly one block runs. Never both, and never neither.
else comes straight after the closing } of the if. It has no condition of its own, because it catches everything the if did not.
<?php
$biscuits = 0;
if ($biscuits === 0) {
echo "Time to go to the shop.\n";
} else {
echo "Have a biscuit!\n";
} Read else as otherwise.
guess first
Full marks or not? Make a guess.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$score = "10";
if ($score === 10) {
echo "Full marks!\n";
} else {
echo "Not quite.\n";
}
your turn
Your turn. Meet a pet that is not a dog.
Type any pet except a dog between the quotes, then press run to see plan B.
fix it
The cinema code will not run. Fix it!
- The ParseError names line 6, but the slip is one line up. Look at what comes after
else. elsecatches everything theifdid not, so it never has a condition of its own.- Delete
($ticket === "no")so line 5 says} else {, then press run.
nailed it
your program has a plan b now. :D
elseruns when theifcondition isfalse.- Only one block runs: the
ifblock or theelseblock. elsehas no condition. It catches everything else.
new words in your collection
- else
This lesson isn’t saved. A free account remembers every lesson you finish.