Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

if, elseif and else

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.

The shortcut

Order your tests from narrowest to widest. Because the first true branch wins, a wide test placed early swallows the narrow cases after it.

Why the order broke the labelStep 1 of 4
  1. The buggy version

    The first test is if ($stock < 5), giving "Only a few left". Below it sits elseif ($stock === 0), giving "Sold out".

Another classic trap: if ($stock = 0) with a single = assigns 0 and then tests it, so it is always false, and the stock is now zero. Compare with ===.

Drills

Answer fast — trust the rule.

quick drill

With $stock = 7, which label does the example print?

quick drill

How many branches of an if / elseif / else chain can run for one value?

quick drill

Which condition means "in stock and under 10"?

quick drill

What is wrong with if ($stock = 0) { ... }?

Remember

  • Test from the most specific case down; the first true branch wins.
  • Shortcut: narrow tests first, wide tests later, else last.
  • Trap: = assigns, === compares, and missing braces hide bugs.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhy does zero say 'a few left'?

A stock label chain checks $stock < 5 first and $stock === 0 second. Explain why a stock of 0 shows "Only a few left" and how to fix the order.