PHP If...Else...Elseif
PHP If, Else, and Elseif: Writing Clear Conditional Logic
Conditional statements let your PHP application make decisions based on user roles, input values, or database states. PHP evaluates each condition inside if (...) as a boolean and runs only the first branch that evaluates to true.
Basic if, elseif, and else Structure
Chain elseif branches when checking mutually exclusive conditions, and finish with else as a fallback. Always wrap branch bodies in curly braces {} so adding a second line never breaks your logic.
<?php
declare(strict_types=1);
$score = 84;
if ($score >= 90) {
$grade = "A";
} elseif ($score >= 80) {
$grade = "B";
} elseif ($score >= 70) {
$grade = "C";
} else {
$grade = "Needs Review";
}
echo "Student Grade: {$grade}" . PHP_EOL;
Ternary Expressions and Guard Clauses
For short two-way assignments, the ternary operator (condition ? trueValue : falseValue) keeps code concise. Inside functions, prefer early-return guard clauses instead of deeply nested if / else pyramids.
<?php
declare(strict_types=1);
function processOrder(array $order): string
{
if (empty($order['items'])) {
return "Rejected: Cart is empty.";
}
if (!($order['paid'] ?? false)) {
return "Pending: Payment required.";
}
$shipping = $order['total'] >= 50 ? "Free" : "$6.99";
return "Confirmed! Shipping: {$shipping}";
}
echo processOrder(['items' => ['Book'], 'paid' => true, 'total' => 65]) . PHP_EOL;
Common Mistakes to Avoid
- Nesting
ifstatements four levels deep: Use earlyreturnorcontinuestatements to keep functions shallow and easy to follow. - Writing
=instead of===: An assignment insideif ($role = 'admin')always evaluates to truthy and overwrites$role. - Using
elseafter an earlyreturn: Once anifbranch returns, the remaining code already acts as theelsepath.
Frequently Asked Questions
Is there any difference between elseif and else if in PHP?
Inside curly braces { ... }, both work identically. However, when using alternative colon syntax (if ($a): ... endif;), only single-word elseif is valid.
When should I use a ternary operator instead of a full if/else?
Use ternary expressions only for short, single-line value assignments. Avoid nested ternaries because they are hard to read and require explicit parentheses in PHP 8.
What values count as falsy inside a PHP if condition?
false, 0, 0.0, "", "0", empty arrays [], and null all evaluate to false in boolean context.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.