PHP
else and elseif
Learn else and elseif chains for alternative cases.
else and elseif
When the if condition is false, use an else branch to run different code. To test several conditions in order, write elseif; the first true condition's block runs and the rest are skipped.
For example, a grade scale: 85 and above 'excellent', 70-84 'good', 50-69 'pass', below 'fail'. Each range is checked in its own elseif branch, and the final else catches the rest.
The elseif chain
In an elseif chain PHP tests conditions top to bottom. The first true branch runs; every elseif and else after it is skipped. When no condition is true, the final else runs.
So it is wise to order branches from most specific to most general. If you check the wider range first, it can wrongly swallow the smaller one.
Exercise Grade evaluation
The $grade variable is already declared. Write an if/elseif/else chain: when $grade >= 85 print 'excellent', when $grade >= 70 print 'good', when $grade >= 50 print 'pass', otherwise print 'fail'. Print with echo.
Show example solution
Write three conditional branches and an else.
Example solution:
<?php
$grade = 78;
// Grade evaluation
if ($grade >= 85) {
echo 'excellent';
} elseif ($grade >= 70) {
echo 'good';
} elseif ($grade >= 50) {
echo 'pass';
} else {
echo 'fail';
}
Test yourself
-
Which branch runs with $score = 72;?
$score = 72;
if ($score >= 85) {
echo 'excellent';
} elseif ($score >= 70) {
echo 'good';
} elseif ($score >= 50) {
echo 'pass';
} else {
echo 'fail';
}
Show answer
good — Correct. 72 is in the 70-84 range, so 'good' is printed.
-
Write the elseif keyword
$score = 72;
if ($score >= 85) {
echo 'excellent';
} ____ ($score >= 70) {
echo 'good';
} else {
echo 'fail';
}
Show answer
$score = 72;
if ($score >= 85) {
echo 'excellent';
} elseif ($score >= 70) {
echo 'good';
} else {
echo 'fail';
}
-
Which branch runs with $n = 2;?
$n = 2;
if ($n > 10) {
echo 'A';
} elseif ($n > 3) {
echo 'B';
} elseif ($n > 1) {
echo 'C';
} else {
echo 'D';
}
Show answer
C — Correct. 2 is greater than 1 but not 3, so branch C runs.
Next lesson: The switch statement