×

php · level 2 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.