PHP if, elseif, and else: Branches and Condition Order
PHP checks if and elseif conditions from top to bottom and runs the first true branch. An else block handles the remaining cases. The examples show what happens at boundary values such as 10, 20, and 30.
Create two paths with if and else
The PHP if reference explains that PHP evaluates the expression in parentheses as a Boolean. If you need an action only when the condition is true, omit else.
Save the code as example.php and run php example.php in a terminal. Replace the file contents to run each later example.
<?php
$value = 15;
if ($value > 10) {
echo "above\n";
} else {
echo "at-or-below\n";
}
With 15, the code prints above. Set the value to 10 or 5 and it prints at-or-below.
Order elseif conditions and cover boundaries
PHP reaches an elseif branch only if all earlier conditions are false. The thresholds below start at 30 and move down. Starting with >= 10 would catch both 25 and 35 before the higher thresholds.
<?php
function band(int $value): string
{
if ($value >= 30) {
return 'top';
} elseif ($value >= 20) {
return 'high';
} elseif ($value >= 10) {
return 'middle';
} else {
return 'low';
}
}
foreach ([5, 10, 15, 20, 25, 30, 35] as $value) {
echo $value, ': ', band($value), PHP_EOL;
}
5 gives low. 10 and 15 give middle, 20 and 25 give high, and 30 and 35 give top.
Adjacent ranges using only > and < can leave values such as 10 uncovered. In this order, using >= includes each lower boundary. Earlier checks already handle the higher ranges.
Use independent if statements for separate actions
Use separate if statements when one value can trigger several actions. Each statement checks its own condition.
<?php
$value = 25;
if ($value >= 10) {
echo "10+\n";
}
if ($value >= 20) {
echo "20+\n";
}
For 25, this prints both 10+ and 20+. Change the second statement to elseif and the first true condition prevents the second line from printing.
Write HTML branches with a colon and endif
With the PHP alternative control structure syntax, open each branch with a colon and close the chain with endif;. This works well for conditional HTML. Use the single word elseif in colon syntax.
<?php $value = 25; ?>
<?php if ($value >= 30): ?>
<p>top</p>
<?php elseif ($value >= 20): ?>
<p>high</p>
<?php else: ?>
<p>below 20</p>
<?php endif; ?>
The script outputs <p>high</p>. In the browser, it appears as a paragraph containing high.
Understand Boolean conversion
if ($value) interprets the value as a Boolean. Integer 0, an empty string, and string '0' are all false in that context. If '0' is valid input and only the empty string should be rejected, compare with $value !== ''. See the PHP Boolean conversion rules for details.
Use an if chain for ranges or different conditions. For comparisons against several fixed values of the same input, consider PHP switch.




