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 leftHow it works:
if (condition)runs its block only when the condition is true.elseifis 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.)elsecatches 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.
The buggy version
The first test is
if ($stock < 5), giving "Only a few left". Below it sitselseif ($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.
With $stock = 7, which label does the example print?
How many branches of an if / elseif / else chain can run for one value?
Which condition means "in stock and under 10"?
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.
