php · level 2 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
The picks one of two values in one line.
1 items looks careless. An if with an else would fix it, but that takes five lines. The ternary operator does it in one: $count === 1 ? "item" : "items". Read it as: is the count 1? If so, item, otherwise items.
The condition comes first, then ? and the value for true, then : and the value for false. Wrap it in brackets when you join it to other text, so PHP knows where it ends.
repeats a string, giving ####. Together they make quick bar charts.
<?php
$votes = ["cats" => 5, "dogs" => 1, "fish" => 3];
foreach ($votes as $pet => $count) {
$word = $count === 1 ? "vote" : "votes";
echo "$pet: " . str_repeat("#", $count) . " $count $word\n";
} Keep each side of a ternary short, and use a full if when either side needs more than one value.
guess first
Coat or T-shirt? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$temp = 8;
$advice = $temp < 10 ? "Wear a coat" : "T-shirt weather";
echo $advice . "\n";
echo "Stars: " . str_repeat("*", 3) . "\n";
your turn
Your turn. Mark a test.
Type a test score from 0 to 100, then run it. Try one score under 50 and one over.
fix it
Only lives left comes out. Can you fix it?
- PHP joins
"You have 1 " . $livesfirst, then asks whether that whole string=== 1. It never is. - The ternary needs brackets of its own, so PHP knows where the choice starts and ends.
- Wrap the ternary:
($lives === 1 ? "life" : "lives"), then press run.
nailed it
your sentences fit every number now. :D
condition ? a : bpicks one of two values.- Wrap a ternary in brackets when you join it to text.
str_repeatrepeats a string, handy for bars.
new words in your collection
- ternary operator
- str_repeat
This lesson isn’t saved. A free account remembers every lesson you finish.