Skip to content

PHP Tutorial Conditional Statements

PHP else Statement

Lesson 82 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

if runs code when a condition is true. Add else to run something different when it is false.

index.php
PHP
<?php
$age = 15;

if ($age >= 18) {
    echo "Adult";
} else {
    echo "Minor";
}
Output
OUTPUT
Minor

Exactly one of the two blocks runs, never both and never neither.

A real example: login state

index.php
PHP
<?php
$isLoggedIn = false;

if ($isLoggedIn) {
    echo "<a href='/logout'>Log out</a>";
} else {
    echo "<a href='/login'>Log in</a>";
}
Output
OUTPUT
<a href='/login'>Log in</a>

A discount rule

index.php
PHP
<?php
$cartTotal = 450;

if ($cartTotal >= 500) {
    $shipping = 0;
} else {
    $shipping = 49;
}

echo "Shipping: $shipping";
Output
OUTPUT
Shipping: 49

The early return pattern

Inside a function, you can often skip else by returning early. The code becomes flatter and easier to read.

index.php
PHP
<?php
function describeAge(int $age): string
{
    if ($age < 0) {
        return "Invalid age";
    }

    if ($age >= 18) {
        return "Adult";
    }

    return "Minor";
}

echo describeAge(20) . "\n";
echo describeAge(-5);
Output
OUTPUT
Adult
Invalid age

Compare that with one deep if ... else if ... else chain. The early return version has no extra nesting.

else needs an if

else cannot stand alone. It always belongs to the if directly above it.

lightbulb
Handle the unusual case first
When a function has a special case (invalid input, empty list), deal with it at the top with return. The main logic then runs without extra nesting.