PHP if-else Statement
In this page:
Standard If-Else
if/else guarantees exactly one of two blocks runs: the if block when the condition is true, the else block when it's false. There's no scenario where neither runs, and none where both do — the two branches are mutually exclusive by construction.
Example: Standard If-Else
<?php
$age = 15;
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
?>
Login to try C/C++/Java/PHP code in the editor
Conditional Assignment
Using if/else purely to set a variable's value based on a condition is common, but for the simplest cases — assigning one of two values — the ternary operator ($x = $cond ? $a : $b;) expresses the identical logic in a single line.
Example: Conditional Assignment
<?php
$cond = true;
$x = $cond ? "yes" : "no";
echo $x;
?>
Login to try C/C++/Java/PHP code in the editor
Boolean Toggles
Boolean variables pair naturally with if/else to make a condition read like plain English: if ($isPremium) { ... } else { ... } is immediately clear about what's being branched on, compared to a condition buried in a more complex expression.
Example: Boolean Toggles
<?php
$isPremium = false;
if ($isPremium) {
echo "Premium features unlocked";
} else {
echo "Upgrade to unlock features";
}
?>
Login to try C/C++/Java/PHP code in the editor
Alternative Syntax
PHP's alternative syntax replaces the curly braces with a colon after the condition and an endif; to close the block. It's rarely used in plain PHP files, but it reads far more cleanly than brace-heavy code when it's interleaved directly inside an HTML template.
Example: Alternative Syntax
<?php $isAdmin = true; ?>
<?php if ($isAdmin): ?>
<p>Admin panel</p>
<?php else: ?>
<p>Access denied</p>
<?php endif; ?>
Login to try C/C++/Java/PHP code in the editor
Array Checks
Calling a function like array_key_exists() or isset() inside your if condition — before you try to read a value from the array — avoids the warning PHP throws when you access a key that isn't actually there.
Example: Array Checks
<?php
$user = ["name" => "Alice"];
if (isset($user['email'])) {
echo $user['email'];
} else {
echo "No email set.";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: