if
The "if" keyword is used in PHP to conditionally execute code based on a certain condition. In this article, we will explore the syntax and usage of the "if"
The PHP if Statement
The if statement is how a PHP program makes decisions. It runs a block of code only when a condition is true, and skips it otherwise. Without it, a script would execute every line top to bottom with no way to branch — if is the foundation of all conditional logic in PHP.
This guide covers the syntax, how PHP decides whether a condition is "true," the else/elseif family, the alternative endif syntax for templates, shortcuts like the ternary and null-coalescing operators, and the mistakes that trip up beginners.
Basic syntax
if (condition) {
// code that runs only when condition is true
}The condition is any expression that PHP can evaluate to true or false. If it's true, the code inside the curly braces runs; if it's false, PHP skips the block and continues after it.
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}
// Output: You are an adult.The braces are optional when the body is a single statement, but always use them — omitting braces is a common source of bugs, because only the first statement is treated as the body:
if ($age >= 18)
echo "Adult"; // runs conditionally
echo " — welcome"; // ⚠️ runs ALWAYS, it is not part of the ifHow PHP evaluates conditions (truthy and falsy)
A condition does not have to be a literal true/false — PHP converts any value to a boolean. These values are falsy (treated as false):
false0and0.0""(empty string) and"0"null- an empty array
[]
Every other value is truthy. This lets you write compact checks:
<?php
$name = "";
if ($name) {
echo "Hello, $name";
} else {
echo "No name provided."; // empty string is falsy
}
// Output: No name provided.To build conditions you typically use comparison and logical operators. See PHP Operators for the full list.
<?php
$temp = 30;
if ($temp > 25 && $temp < 35) { // logical AND
echo "Warm but comfortable.";
}
// Output: Warm but comfortable.Adding else and elseif
if alone handles one path. To provide a fallback, add an else; to test several conditions in order, chain elseif:
<?php
$score = 72;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 70) {
echo "Grade: B";
} elseif ($score >= 50) {
echo "Grade: C";
} else {
echo "Grade: F";
}
// Output: Grade: BPHP checks each condition top to bottom and runs the first block whose condition is true, then stops. Because $score is 72, the >= 90 test fails, >= 70 succeeds, and the rest are skipped.
For dedicated chapters on these, see PHP else, PHP elseif, and the combined if...elseif...else walkthrough. When you have many fixed values to compare against one variable, a switch statement is often clearer.
Nesting if statements
You can place an if inside another to test a second condition only when the first one passed:
<?php
$loggedIn = true;
$role = "admin";
if ($loggedIn) {
if ($role === "admin") {
echo "Welcome to the admin panel.";
} else {
echo "Welcome back.";
}
}
// Output: Welcome to the admin panel.Deep nesting hurts readability — if you find yourself three levels deep, consider combining conditions with && or returning early.
Alternative syntax (if: / endif)
When mixing PHP with HTML in templates, the colon-and-endif form is easier to read than scattered curly braces:
<?php if ($loggedIn): ?>
<p>Welcome back!</p>
<?php else: ?>
<p>Please log in.</p>
<?php endif; ?>This behaves exactly like the brace version; it's purely a matter of style for view files.
Shorthand: ternary and null coalescing
For simple "either/or" assignments, the ternary operator condenses an if/else into one line:
<?php
$age = 16;
$status = ($age >= 18) ? "adult" : "minor";
echo $status;
// Output: minorWhen you only care whether a value exists (and isn't null), the null-coalescing operator ?? is cleaner than an if (isset(...)):
<?php
$config = [];
$timeout = $config["timeout"] ?? 30; // use 30 if the key is missing
echo $timeout;
// Output: 30Worked examples
<?php
// Example 1
$num = 10;
if ($num > 5) {
echo "The number is greater than 5." . PHP_EOL;
}
// Output: The number is greater than 5.
// Example 2
$color = "red";
if ($color == "blue") {
echo "The color is blue.";
} else {
echo "The color is not blue.";
}
// Output: The color is not blue.Common mistakes
=instead of==.if ($x = 5)assigns 5 to$xand is always truthy. Use==(loose) or===(strict, no type juggling) to compare.==vs===. With==,0 == "hello"and"1" == 1can surprise you because PHP converts types. Prefer===when the types should match.- Missing braces around a multi-line body — only the first statement is conditional.
- Confusing truthy values.
if ($value)is false for0,"", and[]; useisset()or=== nullwhen you specifically mean "does this exist."
Conclusion
The if statement lets a PHP program choose what to do at runtime. Master the truthy/falsy rules, reach for elseif/else to handle multiple paths, use the alternative endif syntax in templates, and lean on the ternary and ?? operators for concise assignments. From here, explore PHP loops to repeat actions and the switch statement for value-based branching.