Skip to main content

How to Use an if Statement in PHP

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

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
}
PartWhat 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.
elseOptional. 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:

main.php, which sets $temperature to 24 and echoes It is hot. when it is above 30, It is warm. when it is above 20, and It is cool. otherwise.

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​

Terminal
php main.php
Output
It is warm.

A zsh terminal where php main.php prints 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​

MistakeWhat happensDo this instead
Writing = instead of ==, as in if ($t = 30)No error: it assigns 30 to $t, and the block always runsUse === or == to compare
Comparing with == when types matter0 == '0' is trueUse ===
Ordering conditions from small to large> 20 catches 35 first, so hot is never printedPut the narrowest condition first

Troubleshooting​

SymptomLikely causeFix
The same branch runs whatever the valueAn assignment in the conditionChange = to ===
A branch you expected never runsA condition above it already matchedReorder 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​