← Back to PHP Course | Chapter 4: Control Flow | Lesson 6 of 14

PHP elseif Ladder

Basic elseif Structure

An elseif ladder tests a series of conditions from top to bottom and runs the block belonging to the *first* one that evaluates to true, then skips every condition and block after it — even if a later condition would also have matched.

Example: Basic elseif Structure

php
<?php
$score = 85;
if ($score >= 90) {
    echo "A";
} elseif ($score >= 80) {
    echo "B";
} else {
    echo "C";
}
?>

Multiple elseif Blocks

You can chain as many elseif blocks as the logic needs, which makes this the natural structure when a value needs to be sorted into one of several distinct categories or ranges, rather than just a simple true/false split.

Example: Multiple elseif Blocks

php
<?php
$grade = 72;
if ($grade >= 90) {
    echo "A";
} elseif ($grade >= 80) {
    echo "B";
} elseif ($grade >= 70) {
    echo "C";
} elseif ($grade >= 60) {
    echo "D";
} else {
    echo "F";
}
?>

Ordering Conditions

Because PHP stops at the first true condition, order matters: placing a broad, easily-satisfied condition near the top of the ladder can silently steal cases that were meant to reach a more specific condition further down — always order from most specific to most general.

Example: Ordering Conditions

php
<?php
$age = 25;
if ($age >= 0) {
    echo "Matched too broad first condition";
} elseif ($age >= 18) {
    echo "This never runs -- unreachable";
}
?>

Alternative Colon Syntax

The alternative colon syntax works the same way here as with plain if/else, but PHP requires elseif to be written as one word (not else if) when using this style — a small but easy-to-miss syntax rule specific to the colon form.

Example: Alternative Colon Syntax

php
<?php
$role = "editor";
if ($role === "admin"):
    echo "Admin access";
elseif ($role === "editor"):
    echo "Editor access";
else:
    echo "No access";
endif;
?>

Default Fallback Else

A final else with no condition attached catches every case none of the preceding branches matched. It only ever runs if the entire ladder above it fell through, making it the safety net for values you didn't explicitly plan for.

Example: Default Fallback Else

php
<?php
$day = "Sunday";
if ($day === "Saturday") {
    echo "Weekend";
} elseif ($day === "Monday") {
    echo "Start of week";
} else {
    echo "Some other day";
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.