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.
if, elseif, and else StructureChain 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;
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;
if statements four levels deep: Use early return or continue statements to keep functions shallow and easy to follow.= instead of ===: An assignment inside if ($role = 'admin') always evaluates to truthy and overwrites $role.else after an early return: Once an if branch returns, the remaining code already acts as the else path.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.
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.
if condition?false, 0, 0.0, "", "0", empty arrays [], and null all evaluate to false in boolean context.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.