PHP elseif Ladder
In this page:
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
$score = 85;
if ($score >= 90) {
echo "A";
} elseif ($score >= 80) {
echo "B";
} else {
echo "C";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$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";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$age = 25;
if ($age >= 0) {
echo "Matched too broad first condition";
} elseif ($age >= 18) {
echo "This never runs -- unreachable";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$role = "editor";
if ($role === "admin"):
echo "Admin access";
elseif ($role === "editor"):
echo "Editor access";
else:
echo "No access";
endif;
?>
Login to try C/C++/Java/PHP code in the editor
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
$day = "Sunday";
if ($day === "Saturday") {
echo "Weekend";
} elseif ($day === "Monday") {
echo "Start of week";
} else {
echo "Some other day";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: