Control Flow — PHP

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 customer pays at the cash register of Mrs. Tini's Stall. Mrs. Tini looks at the total, then checks these three rules in order:

  1. If the total is $100 or more: free delivery.
  2. If not, and the total is $50 or more: a 10% discount.
  3. 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

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
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";
}

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

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.

What you will learn