if / elseif / else
Almost every useful script needs to make a decision at some point —
show a discount only for logged-in users, print a different greeting
depending on the time of day, or reject a form when a field is
missing. In PHP, that decision-making is built around the if
statement. You give PHP a condition; if it evaluates to true, one
block of code runs, and if it evaluates to false, PHP either skips
that block or runs an alternative one you provide with elseif or
else. Nothing exotic is happening under the hood, but the small
details — how conditions are evaluated, where the braces go, how
elseif differs from writing else { if (...) } — are exactly the
kind of thing that quietly causes bugs if you are not careful.
The basic if statement
An if statement takes a condition in parentheses and a block of code in curly braces. The block only executes when the condition evaluates to true (or to something PHP treats as "truthy").
A single if
<?php
$temperature = 32;
if ($temperature > 30) {
echo "It's a hot day.";
}It's a hot day.
If $temperature had been 20 instead, the condition would evaluate to false, the block would be skipped entirely, and the script would print nothing at all — there is no else yet, so PHP has nowhere else to go.
Adding an else branch
else gives the statement a fallback: code that runs whenever the if condition was false. Exactly one of the two blocks will ever run.
if / else
<?php
$age = 16;
if ($age >= 18) {
echo "You can vote.";
} else {
echo "You are not old enough to vote yet.";
}You are not old enough to vote yet.
Chaining conditions with elseif
Real-world logic is rarely just two-way. elseif (also written as two words, else if, though elseif is the more idiomatic single keyword in PHP) lets you test additional conditions in order. PHP checks each condition top to bottom and runs the first block whose condition is true; everything after that is skipped, even if a later condition would also have matched.
Grading example with elseif
<?php
$score = 82;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}Grade: B
Notice that $score is 82, which technically also satisfies
$score >= 70. That branch never runs, because PHP stops at the
first matching condition — order matters. If you had written the
conditions from loosest to tightest ($score >= 70 first), every
score of 70 or above would incorrectly print "Grade: C".
elseif vs else if
elseif and else if behave identically in normal curly-brace syntax — PHP treats them as the same thing. The distinction only matters in the alternative syntax described below, where elseif must be written as a single word.
Alternative syntax for templates
Alternative syntax mixed with HTML
<?php $isLoggedIn = true; $username = "Sana"; ?>
<?php if ($isLoggedIn): ?>
<p>Welcome back, <?= $username ?>!</p>
<?php elseif (!$isLoggedIn && isset($username)): ?>
<p>Please log in to continue.</p>
<?php else: ?>
<p>Hello, guest.</p>
<?php endif; ?><p>Welcome back, Sana!</p>
The structure is the same as before — if:, elseif:, else:, then a closing endif; — just without braces. Every if: needs exactly one matching endif;, so it is easy to lose track of nesting in a long template; many teams reserve this syntax for simple, shallow conditionals and switch to curly braces once the logic gets nested.
Nested conditions
An if block can contain another if statement inside it. This is useful when a decision genuinely depends on two separate questions, but nesting more than two or three levels deep usually signals that the logic should be restructured — combined into a single condition with &&/||, or pulled into a small function with an early return.
Nested if for a two-part check
<?php
$isMember = true;
$cartTotal = 120;
if ($isMember) {
if ($cartTotal >= 100) {
echo "You get free shipping and a 10% member discount.";
} else {
echo "You get free shipping as a member.";
}
} else {
echo "Join as a member to unlock free shipping.";
}You get free shipping and a 10% member discount.
The same result can often be written flatter, which is usually easier to follow at a glance:
Flattened with a combined condition
<?php
if ($isMember && $cartTotal >= 100) {
echo "You get free shipping and a 10% member discount.";
} elseif ($isMember) {
echo "You get free shipping as a member.";
} else {
echo "Join as a member to unlock free shipping.";
}Comparison operators recap
Conditions are usually built from comparison operators: == (loose equality), === (strict equality, also checking type), != / !== for inequality, and <, >, <=, >= for ordering. PHP also lets you combine multiple conditions with && (and), || (or), and ! (not).
Strict vs loose comparison inside a condition
<?php
$input = "0";
if ($input == false) {
echo "Loosely equal to false.";
}
if ($input === false) {
echo "This never prints.";
} else {
echo "Strictly, a non-empty string is not the boolean false.";
}Loosely equal to false. Strictly, a non-empty string is not the boolean false.
Common mistake: assignment instead of comparison
One of the oldest bugs in C-family languages, PHP included, is typing a single = where you meant == or ===. = assigns a value and the expression evaluates to that assigned value, so if ($status = "active") does not check anything — it overwrites $status with the string "active" and, because a non-empty string is truthy, the branch always runs.
The classic = vs == bug
<?php
$status = "inactive";
// Bug: single = assigns "active" to $status, then treats it as truthy.
if ($status = "active") {
echo "This always runs, regardless of the real status!";
}
echo "\n$status still got overwritten to: $status";This always runs, regardless of the real status! $status still got overwritten to: active
Common mistake: forgetting braces
PHP allows an if (or else) to control a single statement without braces at all. That is legal, but it becomes a trap the moment someone — often a future version of you — adds a second statement and assumes it is still inside the block.
Looks like two statements are guarded, only one actually is
<?php
$isAuthenticated = false;
if (!$isAuthenticated)
echo "Access denied.";
header("Location: /login"); // NOT part of the if - runs unconditionally!
echo "Continuing script execution regardless of auth...";Access denied. Continuing script execution regardless of auth...
The indentation makes header(...) look like it belongs to the if, but PHP only attaches the single statement immediately after the condition to it. Everything else — including that redirect call — runs unconditionally. This exact shape of bug (a security check that silently stopped protecting anything) has shipped in real applications.
Truthy and falsy values in conditions
A condition does not have to be a comparison — any expression works, and PHP converts it to a boolean. Values that convert to false include 0, 0.0, "" (empty string), "0", null, [] (an empty array), and the boolean false itself. Everything else, including the string "0.0" and any non-empty array, is truthy.
Testing truthiness directly
<?php
$items = [];
if ($items) {
echo "The cart has items.";
} else {
echo "The cart is empty.";
}The cart is empty.
Putting it together
ifruns its block only when the condition is truthy; without anelse, a false condition simply skips the block.elseifchains are checked top to bottom, and only the first matching branch runs — order your conditions from most specific to least specific.The alternative
if: ... elseif: ... else: ... endif;syntax exists for readability inside HTML templates.Nesting is fine for a level or two, but a combined condition or an early return is often clearer.
Watch for
=where you meant==/===, and always use braces, even for one-line bodies.