Lesson 5 of 100
Control flow12 min5 checksPHP 8.5

Choose a Branch with if, elseif and else

Learn how PHP evaluates a condition to a boolean and picks one branch, with attention to boundary values, ordering of checks and truthiness.

01 · THE IDEAREAD → TRY → LEARN

Why conditionals matter

A program that always does the same thing is not very useful. Conditionals let your code look at a value and decide what to do next. The core tool is the if construct. PHP evaluates the expression in parentheses to a boolean. If the result is true, the statement runs. If it is false, PHP skips it.

The basic shape

The simplest form is if (expr) statement. In practice, almost everyone wraps the body in braces so that several statements can be grouped, and so that adding a second line later does not silently fall outside the branch. Add an else for the case where the condition is false.

Example
<?php
$stock = 0;
if ($stock > 0) {
    echo "In stock\n";
} else {
    echo "Sold out\n";
}
Output
Sold out

Exactly one of the two blocks runs. The comparison $stock > 0 produces a boolean, and that boolean selects the branch.

Several branches with elseif

When there are more than two outcomes, chain conditions with elseif. PHP tests them from top to bottom and runs only the first block whose condition is true. Once a branch has run, the rest of the chain is skipped. A final else catches everything that did not match.

This top-to-bottom behavior means order is part of the logic. Put the most specific or most restrictive check first, and let later checks rely on the fact that earlier ones were already false.

Example
<?php
function ticketPrice(int $age): int {
    if ($age < 3) {
        return 0;
    } elseif ($age < 13) {
        return 5;
    } elseif ($age < 65) {
        return 10;
    } else {
        return 7;
    }
}

echo json_encode([ticketPrice(2), ticketPrice(3), ticketPrice(12), ticketPrice(13), ticketPrice(65)]) . "\n";
Output
[0,5,5,10,7]

Notice that the second check is only $age < 13. It does not need to say $age >= 3, because anyone younger than 3 has already been handled. Also look at the values around each limit: 2 and 3, 12 and 13, 64 and 65. Those are boundary cases, and they are where most conditional bugs hide.

Boundaries: < versus <=

The difference between < and <= decides which side of a limit a value falls on. Before writing a condition, say the rule aloud in words: "up to and including 500 grams" means <= 500, while "under 500 grams" means < 500. Then test the exact limit and the values one step on either side.

Truthiness

The condition does not have to be a comparison. PHP converts any value to a boolean. Empty string, "0", 0, 0.0, an empty array and null are all false. Most other values, including "a" and a non-empty array such as [0], are true.

Example
<?php
$values = ["", "0", "a", 0, 0.0, [], [0], null];
$result = [];
foreach ($values as $v) {
    if ($v) {
        $result[] = "true";
    } else {
        $result[] = "false";
    }
}
echo json_encode($result) . "\n";
Output
["false","false","true","false","false","false","true","false"]

The string "0" being false surprises many beginners. When you mean "is this the number zero" or "is this exactly null", write an explicit comparison rather than relying on truthiness.

Common mistakes

  • Using = (assignment) where you meant == or === inside a condition.
  • Forgetting braces and then adding a second statement that always runs.
  • Ordering elseif checks so that a broad condition shadows a narrower one.
  • Off-by-one errors at a limit, such as < where <= was intended.
  • Relying on truthiness when an empty string or 0 is a legitimate value.

Exercise contract

Write a function shippingLabel(int $weightGrams): string that returns a label for a parcel:

  • A weight of 0 or less returns "invalid".
  • Up to and including 500 grams returns "light".
  • Above 500 and up to and including 2000 grams returns "standard".
  • Anything heavier returns "heavy".

Handle the invalid case first, then work upward through the limits. Your function is checked against values on and next to each boundary.

Recap

if runs a block when its condition is true, else covers the rest, and elseif chains further tests that are checked in order with only the first match running. Convert rules into precise comparisons, mind < versus <=, and test the values right at each limit.

Before you start

Types · Operators

You’ll practice
  • Use if, elseif and else
  • Return different values for boundary cases
Your task

Make shippingLabel() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.