← Back to PHP Course | Chapter 4: Control Flow | Lesson 2 of 14

PHP if-else Statement

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
<?php
$age = 15;
if ($age >= 18) {
    echo "Adult";
} else {
    echo "Minor";
}
?>

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
<?php
$cond = true;
$x = $cond ? "yes" : "no";
echo $x;
?>

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
<?php
$isPremium = false;
if ($isPremium) {
    echo "Premium features unlocked";
} else {
    echo "Upgrade to unlock features";
}
?>

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
<?php $isAdmin = true; ?>
<?php if ($isAdmin): ?>
  <p>Admin panel</p>
<?php else: ?>
  <p>Access denied</p>
<?php endif; ?>

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
<?php
$user = ["name" => "Alice"];
if (isset($user['email'])) {
    echo $user['email'];
} else {
    echo "No email set.";
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.