When your web application must evaluate more than two possible outcomes (such as determining university student grades, routing user roles, or categorizing customer support tickets), a simple two-way if...else is insufficient. The elseif statement creates a multi-branch decision ladder that tests several conditions in linear sequence until a matching condition is found.
elseifPHP evaluates conditions from top to bottom. The moment any condition evaluates to true, its code block executes immediately, and the Zend parser completely bypasses all subsequent elseif and else blocks:
<?php
$score = 82;
if ($score >= 90) {
$grade = "A+ (Outstanding)";
} elseif ($score >= 80) {
$grade = "A (Excellent)";
} elseif ($score >= 70) {
$grade = "B (Good)";
} elseif ($score >= 60) {
$grade = "C (Satisfactory)";
} elseif ($score >= 40) {
$grade = "D (Pass)";
} else {
$grade = "F (Supplementary / Fail)";
}
echo "Final Examination Result: " . $grade;
?>
Dynamic websites often customize greeting messages based on the current server hour:
<?php
// Get 24-hour format of current server time (00 to 23)
$currentHour = (int)date("H");
if ($currentHour >= 5 && $currentHour < 12) {
$greeting = "Good Morning! Have a productive day of coding.";
} elseif ($currentHour >= 12 && $currentHour < 17) {
$greeting = "Good Afternoon! Welcome back to Veewom Tutorials.";
} elseif ($currentHour >= 17 && $currentHour < 21) {
$greeting = "Good Evening! Enjoy your coding session.";
} else {
$greeting = "Good Night! Rest well.";
}
echo "<h3>" . $greeting . "</h3>";
?>
elseif vs else ifA favorite question in university viva examinations is the subtle difference between writing elseif as one word versus else if as two words:
| Syntax Format | Curly Brace Syntax ({ }) |
Colon Template Syntax (: endif;) |
|---|---|---|
elseif (One word) |
Valid & Recommended | Valid & Required |
else if (Two words) |
Valid | SYNTAX ERROR! |
<?php $day = "Monday"; ?>
<!-- Valid Colon Syntax: MUST use single-word 'elseif' -->
<?php if ($day === "Saturday" || $day === "Sunday"): ?>
<p>Weekend: College Campus Closed.</p>
<?php elseif ($day === "Friday"): ?>
<p>Half day lectures.</p>
<?php else: ?>
<p>Regular BCA Lectures in session.</p>
<?php endif; ?>
High-Frequency Exam Question:
Q: What happens if multiple conditions in an elseif ladder evaluate to true?
A: Only the first true condition in source code order will execute. Once its block concludes, the entire ladder terminates and all subsequent true conditions are ignored.
Exercise 13.1: Create an electricity billing script based on unit slabs: First 100 units @ Rs 3.00/unit, next 100 units @ Rs 4.50/unit, and units above 200 @ Rs 6.50/unit.
Exercise 13.2: Write a script that checks a temperature variable and classifies weather as "Freezing", "Cold", "Pleasant", "Hot", or "Extreme Heat".