How to Use an if Statement in PHP
Programs make decisions: warn when it's hot, stop when an order isn't paid. PHP's if runs its block only when the condition is true, and elseif and else handle the other cases.
Syntax
if (<condition>) {
// runs when the condition is true
} elseif (<otherCondition>) {
// runs when the first is false and this one is true
} else {
// runs when none were true
}
| Part | What it does |
|---|---|
if (<condition>) | Tests the condition. When it's true, its block runs and the rest is skipped. |
elseif (<otherCondition>) | Optional, and you can have several. Tested only when everything above was false. |
else | Optional. Runs when no condition was true. |
The PHP manual on elseif: "elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to false."
The Example
The example describes the weather from a temperature: hot above 30, warm above 20, cool otherwise. The temperature is 24.
Prerequisites
- PHP for the command line. This guide uses PHP 8.6.0.
Step 1: Write the Code
Create a file named main.php:

<?php
$temperature = 24;
if ($temperature > 30) {
echo "It is hot.\n";
} elseif ($temperature > 20) {
echo "It is warm.\n";
} else {
echo "It is cool.\n";
}
Step 2: Run It
php main.php
It is warm.

24 > 30 was false, so PHP moved on; 24 > 20 was true, so it printed It is warm. and skipped the else. The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Writing = instead of ==, as in if ($t = 30) | No error: it assigns 30 to $t, and the block always runs | Use === or == to compare |
Comparing with == when types matter | 0 == '0' is true | Use === |
| Ordering conditions from small to large | > 20 catches 35 first, so hot is never printed | Put the narrowest condition first |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| The same branch runs whatever the value | An assignment in the condition | Change = to === |
| A branch you expected never runs | A condition above it already matched | Reorder the conditions |
FAQ
Is else if the same as elseif?
With braces, yes: else if worked the same in my check. With the colon syntax, if (...):, only elseif is allowed.
What counts as true?
Any value that isn't falsy. 0, '', '0', null, false and empty arrays are falsy; almost everything else is true.
Conclusion
if runs a block when its condition is true, elseif tries the next condition, and else catches the rest. Compare with ===, and watch for a stray =, which PHP accepts without complaint.
Additional Resources
- if, in the PHP manual.
- elseif/else if, in the PHP manual.
