Skip to the workspace
Pebellslearn by building
Conditionals  ›  Lesson

if, elseif and else

if/else 12 minAn if, elseif and else chain runs only the first branch whose condition is true, so the narrowest tests must come first.

php / if, elseif and else

Explore each scene at your own pace.

01 · The rule

The rule

if, elseif and else

An if, elseif and else chain runs only the first branch whose condition is true, so the narrowest tests must come first.

Trace the first matching branch and check boundary inputs.

Every Pageturn book page shows one of three labels: "In stock", "Only a few left" or "Sold out". The page has to choose, based on the stock count. That choice is an if statement, the most basic decision in any program.

The rule

Test from the most specific case down; the first true branch wins.

<?php
$stock = 3;

if ($stock === 0) {
    $label = "Sold out";
} elseif ($stock < 5) {
    $label = "Only a few left";
} else {
    $label = "In stock";
}

echo $label;   // Only a few left

How it works:

  • if (condition) runs its block only when the condition is true.
  • elseif is checked only when every test above it was false. You may add as many as you need. (else if, as two words, also works with braces.)
  • else catches everything that was left. It is optional.
  • Only one branch runs. As soon as one condition is true, PHP skips all the rest.

Conditions use comparison operators, ===, !==, <, >, <= and >=, joined with && (and), || (or) and ! (not):

if ($stock > 0 && $price < 10) {
    echo "Bargain available!";
}

For a simple either/or value, the ternary operator fits on one line: $label = $stock > 0 ? "In stock" : "Sold out";.

Always use braces, even for one line. It keeps the next person from adding a second line that silently falls outside the if.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.