Thuta Learning
PHP
IntermediateProgrammingBeginner

If...Else...Elseif

PHPLesson 1125 min

What you'll walk away with

  • Explain why only one branch of an if / elseif / else chain runs and why the order matters
  • List the values PHP treats as false and validate input such as "0" correctly
  • Choose between >= and > and test the boundary values
  • Flatten nested ifs with guard clauses

Explain it simply

Explain it simply

An if statement says "when this condition is true, run this code". elseif adds more conditions and else catches everything that is left. Decisions such as whether a user is logged in, stock is available, someone is old enough or a form is valid are all written with these statements.

PHP tests the conditions from top to bottom and runs only the first block whose condition is true. The rest are skipped, even if later conditions are true as well. So the order in which you write the conditions is part of the logic.

Problem → Why → Solution

The problem: a wrong grade with no error

The grading script below raises no error, yet it prints "Grade C" for a student with 95 points. Each line looks normal when you read it, but there is a logic bug. Because nothing warns you, you only catch it by testing.

grade-bug.php
<?php
$score = 95;

if ($score >= 60) {
    echo "Grade C";
} elseif ($score >= 80) {
    echo "Grade B";           // never reached for 80 or more
} elseif ($score >= 90) {
    echo "Grade A";           // never reached either
}

Why does it print Grade C?

95 >= 60 is true, so the first block runs and the two elseif conditions are never even tested. Everyone with 60 points or more lands in that first branch. The fix is to put the strictest condition first and start with >= 90.

Core concept: top to bottom, the first true branch wins

An if statement runs a block only when its condition is true. elseif adds more conditions and else catches everything left. PHP checks them from top to bottom, runs the first block whose condition is true and skips all the others, even if later conditions would also be true. That is why order is part of the logic.

The condition does not have to be a bool; PHP converts it using truthiness. These values count as false: false, 0, 0.0, '' (the empty string), '0', [] (the empty array) and null. Everything else is true, including '0.0', 'false', ' ' and [0]. So if ($input) is false for the text '0', which can be a valid answer on a form. When the exact value matters, compare explicitly: if ($input === '') or if ($input !== null).

= assigns and == compares. if ($a = 5) assigns 5 to $a and is always true, and PHP 8 does not warn about it. Boundaries need the right operator: >= includes the limit, > excludes it. For ranges the common bug is off-by-one at the edges, so test the exact boundary values such as 59, 60, 89 and 90.

Prefer flat code. A guard clause checks the bad case first and leaves early with return, throw, exit or continue, so the main path is not buried in nested braces. When every branch compares one value for equality, switch or match reads better (next lesson). PHP also has an alternative syntax, if (...): ... elseif (...): ... else: ... endif;, which is easier to read between HTML tags. In the colon form, writing else if as two words is a parse error; only elseif works.

Mental model: the first true branch wins
  1. Test the first condition
  2. If true, run it and skip the rest
  3. If false, test the next condition
  4. else runs only when nothing matched

Put the strictest condition at the top and the broader ones below it.

General pattern

php
<?php
if (condition) {
    // runs when the condition is truthy
} elseif (otherCondition) {
    // runs only if the first one was false
} else {
    // runs when none of the conditions matched
}

elseif and else are optional, and you can add as many elseif branches as you need. Even when a block holds a single statement, keeping the braces { } is the safer habit.

Example: turning a score into a grade

This example turns the score 82 into a grade. Notice that the conditions run from the highest limit to the lowest, the opposite of the buggy script above. 82 is 80 or more, so it lands in Grade B.

php
<?php
$score = 82;

if ($score >= 90) {
  echo "Grade A";
} elseif ($score >= 80) {
  echo "Grade B";
} elseif ($score >= 60) {
  echo "Grade C";
} else {
  echo "Try again. Practice is the real cheat code.";
}
?>

Code breakdown

  1. Line 4if ($score >= 90) {

    The strictest condition is tested first. 82 >= 90 is false, so this block is skipped. Because of >=, exactly 90 also earns Grade A.

  2. Line 6} elseif ($score >= 80) {

    This is only tested after the first condition failed. At this point the score is known to be below 90, so >= 80 is enough; you do not need to write "between 80 and 89".

  3. Line 7echo "Grade B";

    82 >= 80 is true, so this line runs and the whole chain is left; the later elseif and else are never tested.

  4. Line 10} else {

    else has no condition; it runs only when every test above failed. Here it catches scores below 60.

  5. Line 13?>

    ?> closes PHP mode. A file that contains only PHP does not need it, and leaving it out avoids stray spaces or newlines after the closing tag being sent as output.

You should see
Grade B

Truthiness: which values count as false

The script below shows how each value is treated inside an if. The first seven are falsy and the rest are truthy. Pay special attention to '0' being falsy while '0.0' and '00' are truthy.

truthiness.php
<?php
$values = [false, 0, 0.0, "", "0", [], null, "0.0", "false", " ", "00", [0]];

foreach ($values as $v) {
    $shown = is_array($v) ? json_encode($v) : var_export($v, true);
    echo str_pad($shown, 8) . ($v ? "truthy" : "falsy") . PHP_EOL;
}

Guard clauses and flat code

Checking the bad cases first and returning immediately reads far better than nesting if inside if inside if. The last line of the function then becomes the main path, "everything is fine", and every error message sits right next to its own condition, which makes maintenance easier.

guard-clauses.php
<?php
function describeOrder(?array $order): string
{
    if ($order === null) {
        return "No order found.";
    }
    if (empty($order["items"])) {
        return "The order is empty.";
    }
    if (($order["total"] ?? 0) <= 0) {
        return "The total must be positive.";
    }
    return "Order OK: " . count($order["items"]) . " item(s), total " . $order["total"];
}

echo describeOrder(null) . PHP_EOL;
echo describeOrder(["items" => []]) . PHP_EOL;
echo describeOrder(["items" => ["pen"], "total" => 0]) . PHP_EOL;
echo describeOrder(["items" => ["pen", "book"], "total" => 4500]) . PHP_EOL;

Alternative syntax and the ternary

The alternative syntax uses : and endif; instead of { }. It is popular in templates that mix PHP with HTML because you never hunt for which brace closes which block. When you only need to pick one value, a ternary does it in a single line, but once it gets more complicated than a single condition, go back to if.

alternative-syntax.php
<?php
$stock = 0;

if ($stock > 0):
    echo "In stock";
elseif ($stock === 0):
    echo "Sold out";
else:
    echo "Invalid stock value";
endif;
echo PHP_EOL;

$label = $stock > 0 ? "In stock" : "Sold out";
echo $label . PHP_EOL;

elseif, not else if

In the colon form, writing else if as two words gives Parse error: syntax error, unexpected token "if", expecting ":". With braces both spellings work, but always writing elseif is the safer habit.

In real projects

Where this shows up in real projects

A login flow is an if chain: does the user exist, is the password right, is the account active, checked one step at a time. Quantity-based discount tiers, picking a shipping fee by region, and checking whether a file exists before showing an error message are all written with if and elseif.

Guard clauses are central to error handling. In form validation you check each field, collect the problems in an array and finish with if (empty($errors)) to continue only on success. Put permission checks at the top of a function and stop at once when access is denied. When the number of branches grows large, say ten or more, consider replacing them with a data array or match, which is easier to read and to test.

Common mistakes

Common mistakes

1. Putting the conditions in the wrong order

Putting $score >= 60 before $score >= 90 gives 95 points a Grade C, and with no error you will only notice by testing. Start from the highest limit and try boundary values such as 59, 60, 89 and 90.

2. Confusing = and ==

if ($x = 5) stores 5 in $x and is always true, so it prints "five" and leaves $x changed afterwards. PHP 8 gives no warning for this, so make === a habit.

3. Using if ($input) without knowing "0" is false

When a form sends an age or quantity of '0', if ($_POST['qty']) is false and you conclude "nothing was filled in". Write the decision precisely with if ($_POST['qty'] !== '') or isset().

4. Writing two statements without braces

In if ($ok) echo 'a'; echo 'b'; the second echo has nothing to do with the if and always runs, no matter how you indent it. Use { } even for a single statement.

Best practices

Best practices

  • Order conditions from strictest to broadest and test the boundary values.
  • Check the bad cases first with guard clauses and return early to keep the code flat.
  • Validate input precisely with === '', !== null and isset() instead of relying on truthiness, and always write the braces { }.

Mini challenge

Mini challenge: a ticket price

Write a ticketPrice() function that returns a museum ticket price from an age and a student flag. Check that it is right on the boundary ages (2, 3, 12, 13, 17, 18, 64, 65).

  • Return "invalid age" for an age below 0
  • Return "free" for ages below 3 or from 65 up
  • Return "2000 MMK" for ages 3 to 12, and "3000 MMK" for ages 13 to 17 or for students
  • Return "5000 MMK" for the remaining adults; use an if/elseif/else chain or guard clauses, whichever you prefer
ticket.php
<?php
function ticketPrice(int $age, bool $isStudent): string
{
    // TODO: decide the order of the conditions first (strictest limit on top)
    // TODO: handle invalid ages, then free tickets, then the paid tiers
}

// TODO: loop over several [age, isStudent] pairs and echo each result

Expected: Expected output: Age 2: free Age 8: 2000 MMK Age 13: 3000 MMK Age 30 (student): 3000 MMK Age 30: 5000 MMK Age 65: free Age -1: invalid age

Show hint

Check the invalid age first and combine the free cases with ||. The student discount should only affect adults, so test "65 or older" before the student condition.

Show solution
ticket.php
<?php
function ticketPrice(int $age, bool $isStudent): string
{
    if ($age < 0) {
        return "invalid age";
    } elseif ($age < 3 || $age >= 65) {
        return "free";
    } elseif ($age <= 12) {
        return "2000 MMK";
    } elseif ($age <= 17 || $isStudent) {
        return "3000 MMK";
    }
    return "5000 MMK";
}

$cases = [
    [2, false], [8, false], [13, false], [30, true],
    [30, false], [65, false], [-1, false],
];

foreach ($cases as [$age, $isStudent]) {
    $note = $isStudent ? " (student)" : "";
    echo "Age $age$note: " . ticketPrice($age, $isStudent) . PHP_EOL;
}

Quick quiz 1 / 3

$n = 95; if ($n >= 60) { echo "C"; } elseif ($n >= 90) { echo "A"; } prints what?

Quick quiz 2 / 3

What does if ("0") { echo "yes"; } else { echo "no"; } print?

Quick quiz 3 / 3

$x = 3; if ($x = 5) { echo "five"; } echo $x; prints what?

What to remember

  • In an if / elseif / else chain PHP tests from the top and runs only the first true block, so order is logic.
  • false, 0, 0.0, '', '0', [] and null are falsy and everything else is truthy; compare input exactly.
  • Never confuse = with ==; choose >= or > carefully and test boundary values such as 59, 60, 89 and 90.
  • Keep code flat with guard clauses, and use elseif as one word in the colon syntax.

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

If...Else...Elseif | Thuta Learning