A customer pays at the cash register of Mrs. Tini's Stall. Mrs. Tini looks at the total, then checks these three rules in order:
- If the total is $100 or more: free delivery.
- If not, and the total is $50 or more: a 10% discount.
- If not that either: the normal price.
Mrs. Tini starts at rule 1 and stops at the first rule that fits.
Code often has to choose too: which lines run depends on the situation. The way code chooses which lines run is called control flow. In code, each of Mrs. Tini's rules becomes a condition, and if checks the conditions exactly the way she does: from the top, stopping at the first condition that fits.
if, elseif, else: checked from the top
These are Mrs. Tini's rules in PHP, with one more rule: free crackers for a total of $25 or more.
<?php
$total = 60;
if ($total >= 100) {
echo "Free delivery";
} elseif ($total >= 50) {
echo "10% discount";
} elseif ($total >= 25) {
echo "Free crackers";
} else {
echo "Normal price";
}
This is what PHP does for $total = 60:
| Condition | Result | What happens |
|---|---|---|
$total >= 100 |
false |
skip, check the next one |
$total >= 50 |
true |
print 10% discount, done |
$total >= 25 |
not checked | skipped |
else |
not checked | skipped |
if (condition) { ... }: a condition is a piece of code whose result istrueorfalse. When it istrue, the code inside the curly braces runs.elseifis only checked when every condition above it wasfalse. You can also write itelse if.elsehas no condition.elseruns when none of the conditions wastrue.- Each part (
if,elseif,else) is called a branch. At most one branch runs. As soon as one branch runs, the rest are skipped.
The comparison operators you will use most: >= (greater than or equal to), >, <=, <, === (exactly equal: value and type) and !== (not exactly equal). Two conditions can be joined with && (and) or || (or), and ! flips the result: true becomes false, and false becomes true.
A total of exactly $50 gets 10% discount, because 50 >= 50 is true. So a value right on the boundary goes into that branch.
The order of conditions decides the result
These are the same conditions in reverse order, for a total of 120:
<?php
$total = 120;
if ($total >= 25) {
echo "Free crackers";
} elseif ($total >= 50) {
echo "10% discount";
} elseif ($total >= 100) {
echo "Free delivery";
}
// Output: Free crackers
120 >= 25 is already true at the first check, so Free crackers is printed and the two conditions below it are never checked. So with >=, start from the highest boundary and go down.
The boundary has to be right too. If >= 50 in the first code is written > 50, a total of exactly $50 no longer meets that condition and drops to Free crackers.
Values that count as false
A condition doesn't have to be a comparison. if ($quantity) works too: PHP turns the value into true or false first. Only these count as false (falsy): false, 0, 0.0, "" (empty string), "0", null, and [] (empty array). Everything else is true (truthy), including "0.0", " " (a string with one space), "false" and -1.
In this code, 0 and "0" both count as false:
<?php
$quantity = 0;
echo $quantity ? "Has orders" : "No orders yet"; // No orders yet
$code = "0";
if ($code) {
echo "true";
} else {
echo "false"; // this one runs: "0" counts as false
}
condition ? A : B is called a ternary: a short if-else that produces a value. When the condition is true the result is A, when it is false the result is B.
match: one value, many choices
match turns the status of an order into a sentence for the customer:
<?php
$status = "cooking";
echo match ($status) {
"new" => "Order received",
"cooking" => "Being cooked",
"ready" => "Ready to deliver",
default => "Unknown status",
};
// Output: Being cooked
matchcompares$statuswith each value left of=>using===: the value and its type must be the same. For example, with$table = "1"(form input is always a string),match ($table)doesn't match1 =>, only"1" =>.- The result of
matchis a value, so you canechoit right away or store it in a variable. Close it with;after the}. defaultis used when nothing matches. Withoutdefault, a value that isn't listed, such as"delivered", stops the script:
Fatal error: Uncaught UnhandledMatchError: Unhandled match case 'delivered' in /app/stall.php:4
For ranges of values, write match (true). PHP calculates each condition on the left, from the top. The first condition that is true decides the result: the value on its right.
$label = match (true) {
$total >= 100 => "Free delivery",
$total >= 50 => "10% discount",
default => "Normal price",
};
switch: the older form with break
switch is the older way to choose which code runs, based on one value:
<?php
$day = "Friday";
switch ($day) {
case "Monday":
echo "Shop at the market";
break;
case "Friday":
echo "Special menu: Spiced Rice";
break;
default:
echo "Regular menu";
}
- Each
casenames one value to compare$daywith.breakstops theswitchthere. Withoutbreak, PHP continues and runs the code of thecasebelow it (fall-through). switchcompares with==(loose):"1"and1count as equal, and so do"01"and1.matchdoesn't, because it uses===. For new code,matchis usually the safer choice.==has other surprises, for examplenull == falseand"1e3" == "1000"are bothtrue(the rules are in the==and===section of the Advanced Type System lesson).
When the value is null: ??
This order has no "note" key:
<?php
$order = ["menu" => "Iced Tea"];
echo $order["note"] ?? "no note"; // no note
a ?? b means: use a if it exists and isn't null, otherwise use b. Without ??, reading a key that doesn't exist gives Warning: Undefined array key "note". Remember, ?? only replaces a value that is null or missing: a note holding "" is still printed, empty.
Later, in the OOP lesson, you'll meet objects. An operator similar to ??, ?->, reads from an object that may be null. When $customer is null, $customer->name gives Warning: Attempt to read property "name" on null, while $customer?->name just gives null. So $customer?->name ?? "Guest" gives "Guest".
⚠️ When the wrong branch runs
- Conditions in reverse order. The smallest boundary is checked first, so every big value falls into it. With
>=, order from the highest. >when you meant>=. A value right on the boundary ($50, or a score of 70 in the exercise) drops to the branch below.=insideif.if ($total = 0)puts 0 into$totalinstead of comparing, so the result is alwaysfalseand the total is gone. Compare with===.matchwithoutdefault. A value that isn't listed causes anUnhandledMatchErrorand the script stops.
TL;DR: if/elseif/else is checked from the top, and only the first branch (part) whose condition is true runs. So order >= boundaries from the highest, and use >= so a value right on the boundary is included. What counts as false: false, 0, 0.0, "", "0", null, []. condition ? A : B is a short if-else. match picks a result from one value, compares with ===, and produces a value. Without default, a value that doesn't match causes an UnhandledMatchError. switch compares with ==, and each case needs break. a ?? b uses b when a is null or missing.
⚡ Checked from the top
Write:
<?php
$total = 60;
if ($total >= 100) {
echo "Free delivery";
} elseif ($total >= 50) {
echo "10% discount";
} elseif ($total >= 25) {
echo "Free crackers";
} else {
echo "Normal price";
}
Guess first: what gets printed?
10% discount. 60 >= 100 is false, 60 >= 50 is true, and the rest are never checked.
Meaning: At most one branch (the if, elseif or else part) runs: the first one whose condition is true. With >=, order the boundaries from the highest, and a value right on a boundary goes into that branch.
⚡ Values that count as false
Guess first: $code = "0"; if ($code) { ... }, does the code inside the if run?
No. The string "0" counts as false, just like false, 0, 0.0, "", null and [].
Meaning: A condition doesn't have to be a comparison. PHP turns the value in the if brackets into true or false first.
⚡ match compares with ===
Write:
<?php
$status = "cooking";
echo match ($status) {
"new" => "Order received",
"cooking" => "Being cooked",
"ready" => "Ready to deliver",
default => "Unknown status",
};
Meaning: match compares $status with the values left of =>, type included, then produces the value on the right: Being cooked. default is used when nothing matches. Without default, a value that isn't listed causes an UnhandledMatchError.