When there are more than two possibilities, chain extra conditions with elseif.
<?php
$score = 72;
if ($score >= 90) {
echo "Grade A";
} elseif ($score >= 75) {
echo "Grade B";
} elseif ($score >= 60) {
echo "Grade C";
} else {
echo "Fail";
}
Grade C
How it runs
PHP checks the conditions from top to bottom and runs the first block whose condition is true. It then skips the rest.
For a score of 72:
72 >= 90? No.72 >= 75? No.72 >= 60? Yes, so printGrade Cand stop.
Order matters
Because the chain stops at the first match, put the strictest condition first. This version is wrong:
<?php
$score = 95;
if ($score >= 60) {
echo "Grade C";
} elseif ($score >= 90) {
echo "Grade A";
}
Grade C
A score of 95 matches the first condition, so the elseif never runs.
else is optional
The last else catches everything that did not match. Leave it out if you do not need it.
<?php
$temperature = 38;
if ($temperature >= 40) {
echo "Very hot";
} elseif ($temperature >= 30) {
echo "Hot";
} elseif ($temperature >= 20) {
echo "Pleasant";
}
Hot
elseif vs else if
elseif (one word) and else if (two words) work the same with braces. In the alternative syntax (if: ... endif;), you must use the one-word elseif.
When the chain gets long
If you compare one value against many fixed options, a match expression is shorter than a long elseif chain.
Exercise: shipping cost
Orders under 500 pay 60. Orders from 500 to 999 pay 30. Orders from 1000 up ship free. Print the shipping cost for an order of 750.
Show a possible solution
<?php
$order = 750;
if ($order >= 1000) {
$shipping = 0;
} elseif ($order >= 500) {
$shipping = 30;
} else {
$shipping = 60;
}
echo "Shipping: $shipping";
Shipping: 30