PHP If...Else...Elseif
What Are Conditional Statements? In simple terms: Conditional statements let a program make decisions. They run different code depending on whether a condition is true or false — for example, showing
What Are Conditional Statements?
In simple terms: Conditional statements let a program make decisions. They run different code depending on whether a condition is true or false — for example, showing "Welcome back" to logged-in users and a login button to everyone else.
Technically: A conditional statement evaluates an expression, converts the result to a boolean, and chooses which block of code to execute. Code that is not chosen is skipped entirely.
Why They Matter
Without conditions, a program would do the same thing every time. Every real application depends on decisions:
- Is the user logged in? Do they have permission?
- Is the form input valid?
- Is the item in stock? Does the order qualify for free shipping?
- Did the payment succeed or fail?
Conditional Statements in PHP
| Statement | Use When |
|---|---|
if | Run code only when a condition is true |
if...else | Choose between two paths |
if...elseif...else | Choose between several paths, checked in order |
switch | Compare one value against many possible values (loose comparison) |
match | Return a value based on one value, with strict comparison (PHP 8.0+) |
Ternary ?: | Choose between two values in a single expression |
Null coalescing ?? | Provide a fallback for a missing or null value |
This lesson gives an overview of the if family and how the forms relate. Each form is covered in depth in its own lesson: PHP If, PHP If...Else, PHP Shorthand if, PHP Nested if, PHP Switch, and PHP Match.
if — Run Code When a Condition Is True
Syntax
if (condition) {
// runs only when condition is true
}
Example
<?php
$stock = 3;
if ($stock < 5) {
echo "Only $stock left — order soon!\n";
}
echo "Product page loaded.\n";
Output
Only 3 left — order soon!
Product page loaded.
The message inside the block appears only because $stock < 5 is true. The last line runs in every case, because it is outside the if.
if...else — Choose Between Two Paths
Syntax
if (condition) {
// runs when condition is true
} else {
// runs when condition is false
}
Example
<?php
$isLoggedIn = false;
if ($isLoggedIn) {
echo "Welcome back!\n";
} else {
echo "Please log in to continue.\n";
}
Output
Please log in to continue.
Exactly one of the two blocks runs — never both, never neither.
if...elseif...else — Choose Between Several Paths
Syntax
if (condition1) {
// runs when condition1 is true
} elseif (condition2) {
// runs when condition1 is false and condition2 is true
} elseif (condition3) {
// runs when the earlier conditions are false and condition3 is true
} else {
// runs when none of the conditions are true
}
Example: Grade Calculator
<?php
function grade(int $score): string
{
if ($score >= 90) {
return 'A';
} elseif ($score >= 75) {
return 'B';
} elseif ($score >= 60) {
return 'C';
} elseif ($score >= 40) {
return 'D';
} else {
return 'F';
}
}
foreach ([95, 82, 67, 45, 30] as $score) {
echo "$score => " . grade($score) . "\n";
}
Output
95 => A
82 => B
67 => C
45 => D
30 => F
How PHP Evaluates the Chain
- Conditions are checked from top to bottom.
- The first condition that is true runs its block, and the rest of the chain is skipped.
- If no condition is true, the
elseblock runs (if there is one).
For a score of 82:
82 >= 90 ? false → check next
82 >= 75 ? true → return 'B' (remaining conditions are never checked)
Why Order Matters
Because only the first true condition is used, conditions must go from the most specific to the least specific. Reversing the order breaks the logic:
<?php
$score = 95;
if ($score >= 40) {
echo "D\n";
} elseif ($score >= 90) {
echo "A\n";
}
Output
D
95 >= 40 is true, so the chain stops immediately, and the A branch is unreachable for every score. With a "greater than or equal" chain, start with the highest threshold.
Visualizing the Flow
┌─────────────────┐
│ condition 1 ? │
└───────┬─────────┘
true │ false
┌────────────┘ └────────────┐
▼ ▼
[ block 1 ] ┌─────────────────┐
│ │ condition 2 ? │
│ └───────┬─────────┘
│ true │ false
│ ┌────────────┘ └──────────┐
│ ▼ ▼
│ [ block 2 ] [ else block ]
│ │ │
└────────────────┴──────────────┬──────────────┘
▼
code after the statement
Whichever path is taken, execution continues with the code after the entire if statement.
elseif vs else if
PHP accepts both spellings when you use curly braces:
<?php
$temperature = 28;
if ($temperature > 35) {
echo "Hot\n";
} elseif ($temperature > 25) {
echo "Warm\n";
} else if ($temperature > 15) {
echo "Mild\n";
} else {
echo "Cool\n";
}
Output
Warm
elseifis a single keyword.else ifis technically anelsewhose body is a newifstatement. With braces, both behave identically.
With the alternative syntax used in templates (if: ... endif;), only elseif works; else if: is a parse error. For consistency, use elseif everywhere — it is also what coding standards such as PER Coding Style recommend.
The Same Decision in Different Forms
Different conditional forms suit different situations. Here is one decision — a shipping label based on cart total — written three ways.
<?php
$cartTotal = 1200;
// 1. if...elseif...else
if ($cartTotal >= 2000) {
$shipping = 'Free express shipping';
} elseif ($cartTotal >= 999) {
$shipping = 'Free standard shipping';
} else {
$shipping = '₹79 shipping';
}
echo $shipping . "\n";
// 2. match (true) — returns a value, PHP 8.0+
$shipping = match (true) {
$cartTotal >= 2000 => 'Free express shipping',
$cartTotal >= 999 => 'Free standard shipping',
default => '₹79 shipping',
};
echo $shipping . "\n";
// 3. Ternary — only suitable for two outcomes
$shipping = $cartTotal >= 999 ? 'Free shipping' : '₹79 shipping';
echo $shipping . "\n";
Output
Free standard shipping
Free standard shipping
Free shipping
The ternary version can express only two outcomes, so it cannot distinguish express shipping; it is shown to illustrate where each form fits.
Choosing a Form
| Situation | Best Choice |
|---|---|
| Run extra code only in one case | if |
| Two different actions | if...else |
| Several ranges or unrelated conditions, possibly with multiple statements per branch | if...elseif...else |
| Assign one of several values based on conditions | match (true) |
| Compare one value against a list of exact values | match (or switch for multiple statements) |
| Choose between two short values | Ternary ?: |
| Default for a missing/null value | ?? |
Conditions Are Converted to Boolean
The condition can be any expression. PHP converts its result to true or false using truthiness rules: 0, 0.0, "", "0", [], and null are false; almost everything else is true.
<?php
$cartItems = [];
$couponCode = "0";
if ($cartItems) {
echo "Cart has items\n";
} else {
echo "Cart is empty\n";
}
if ($couponCode) {
echo "Coupon entered\n";
} else {
echo "No coupon\n";
}
Output
Cart is empty
No coupon
The second result is a bug if "0" is a valid coupon code: the string "0" is falsy. Explicit conditions avoid this — if ($couponCode !== ''). Writing precise conditions is covered in PHP If Operators.
Common Mistakes
Wrong Order in an elseif Chain
Effect: Later branches are unreachable.
Fix: Order conditions from most specific to least specific (for example, highest threshold first).
Using = Instead of ===
Effect: if ($status = 'paid') assigns and is always true.
Fix: Use ===.
Separate if Statements Where elseif Was Intended
<?php
$score = 95;
if ($score >= 90) { echo "A\n"; }
if ($score >= 75) { echo "B\n"; }
Output
A
B
Independent if statements are all checked, so several can run. Use elseif when the cases are mutually exclusive.
Relying on Truthiness for Strings and Numbers
Effect: "0" and 0 are treated as "nothing".
Fix: Compare explicitly: !== '', !== null, > 0.
Forgetting the Final else
Effect: No branch runs for unexpected values, leaving variables undefined.
Fix: Add an else (or initialize the variable before the chain) to handle every remaining case.
Best Practices
- Always use curly braces, even for single-line blocks.
- Use
elseif(one word) consistently. - Order
elseifconditions carefully and include anelsefor unexpected cases. - Prefer
match (true)when every branch only assigns or returns a value. - Keep conditions explicit; extract complex conditions into well-named variables or functions.
Official reference: https://www.php.net/manual/en/control-structures.elseif.php