PHP If Else Statements: Syntax and Practical Examples

Most PHP applications spend a surprising amount of time making small decisions. Show the dashboard or the login form. Accept the input or display an error. Apply the discount or quietly disappoint the customer.

PHP uses if, elseif and else statements to control these decisions. A condition is evaluated, and PHP executes the first matching block of code.

This guide explains the syntax with practical examples, including strict comparisons, multiple conditions and the alternative syntax used in PHP templates.

How PHP if, elseif and else work

A PHP conditional chain can contain three parts:

  • if checks the first condition.
  • elseif checks another condition when the earlier conditions are false.
  • else provides a default block when no condition matches.
if ($conditionOne) {
    // Runs when condition one is true.
} elseif ($conditionTwo) {
    // Runs when condition one is false and condition two is true.
} else {
    // Runs when neither condition is true.
}

PHP evaluates the conditions from top to bottom. It stops after finding the first condition that evaluates to true. Only one block in the chain is executed.

Conditions commonly use PHP comparison and logical operators such as ===, >=, && and ||.

PHP if statement

Use an if statement when code should run only when a condition is true.

$orderTotal = 120;

if ($orderTotal >= 100) {
    echo "Free delivery applied.";
}

The comparison $orderTotal >= 100 returns true, so PHP displays the message. When the order total is below 100, PHP skips the block and continues with the next statement in the script.

Curly braces are technically optional when an if statement contains only one instruction. It is still safer to include them. A harmless one-line condition has a habit of gaining a second line six months later.

Checking a string value with strict comparison

The next example checks a user role before displaying an administration link.

$userRole = "admin";

if ($userRole === "admin") {
    echo "Open administration panel";
}

The strict comparison operator === checks both the value and its type. It is generally more predictable than ==, which may convert values before comparing them.

The PHP manual provides the complete reference for the PHP if control structure.

PHP if else statement

Use an else block when you need one action for a true condition and another action for a false condition.

$isLoggedIn = false;

if ($isLoggedIn) {
    echo "Welcome back.";
} else {
    echo "Please sign in.";
}

Because $isLoggedIn is false, PHP skips the first block and executes the else block.

An else statement does not have its own condition. It runs only when the associated if condition is false.

Using if else with form input

Conditional statements are often used to validate submitted form values. The following example checks whether a username contains any non-whitespace characters.

<?php
$username = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $username = trim($_POST["username"] ?? "");

    if ($username !== "") {
        $message = "Hello, " . htmlspecialchars(
            $username,
            ENT_QUOTES,
            "UTF-8"
        ) . ".";
    } else {
        $message = "Please enter your username.";
    }
}
?>

<form method="post">
    <label for="username">Username</label>
    <input
        type="text"
        id="username"
        name="username"
        value="<?= htmlspecialchars(
            $username,
            ENT_QUOTES,
            "UTF-8"
        ) ?>"
    >
    <button type="submit">Continue</button>
</form>

<?php if (isset($message)): ?>
    <p><?= $message ?></p>
<?php endif; ?>

The null coalescing operator supplies an empty string when the form field is missing. The submitted value is trimmed before it is checked, so a string containing only spaces is treated as empty.

The example also escapes the username before adding it to the HTML response. A condition can decide whether data is displayed, but it does not make untrusted data safe by itself. Use an appropriate output-escaping function such as htmlspecialchars() when inserting text into HTML.

PHP elseif statement

Use elseif when more than two outcomes are possible. Each condition is checked in order until PHP finds the first true condition.

$score = 82;

if ($score >= 90) {
    $grade = "A";
} elseif ($score >= 75) {
    $grade = "B";
} elseif ($score >= 60) {
    $grade = "C";
} else {
    $grade = "D";
}

echo $grade;

This example prints B. Although a score of 82 also satisfies $score >= 60, PHP never reaches that condition because the earlier $score >= 75 condition already matched.

The order matters. Start with the most restrictive or highest condition. Reversing the checks would produce the wrong result:

$score = 82;

if ($score >= 60) {
    $grade = "C";
} elseif ($score >= 75) {
    $grade = "B";
} elseif ($score >= 90) {
    $grade = "A";
}

Here, every score of 60 or more receives C. The later conditions are unreachable for those values.

PHP accepts both elseif and else if when curly-brace syntax is used. The single-word form is clearer and is required when using PHP’s alternative control-structure syntax.

Checking multiple conditions

Logical operators let an if statement evaluate more than one requirement.

Require all conditions with &&

The logical AND operator, &&, returns true only when every connected condition is true.

$age = 24;
$hasTicket = true;

if ($age >= 18 && $hasTicket === true) {
    echo "Entry permitted.";
}

Accept either condition with ||

The logical OR operator, ||, returns true when at least one connected condition is true.

$isOwner = false;
$isAdministrator = true;

if ($isOwner === true || $isAdministrator === true) {
    echo "You may edit this record.";
}

Reverse a condition with !

The logical NOT operator, !, reverses a Boolean value.

$isBlocked = false;

if (!$isBlocked) {
    echo "Account access is active.";
}

Parentheses make longer conditions easier to read and remove doubt about evaluation order.

$isMember = true;
$orderTotal = 75;
$hasCoupon = false;

if ($isMember && ($orderTotal >= 50 || $hasCoupon)) {
    echo "Discount applied.";
}

The discount is applied when the customer is a member and either has an order of at least £50 or supplies a coupon. The grouped expression states that rule directly, which is much easier to maintain than relying on memory of operator precedence.

Using alternative syntax in PHP templates

PHP provides an alternative syntax for control structures. It replaces curly braces with a colon and closes the block with endif.

This style is useful when PHP conditions are mixed with larger sections of HTML.

<?php
$isLoggedIn = true;
$userName = "Vincy";
?>

<?php if ($isLoggedIn): ?>
    <p>
        Welcome,
        <?= htmlspecialchars($userName, ENT_QUOTES, "UTF-8") ?>.
    </p>
<?php else: ?>
    <p>Please sign in to continue.</p>
<?php endif; ?>

The same syntax works with elseif:

<?php if ($status === "paid"): ?>
    <p>Payment received.</p>
<?php elseif ($status === "pending"): ?>
    <p>Payment is being processed.</p>
<?php else: ?>
    <p>Payment failed.</p>
<?php endif; ?>

Use elseif as one word with alternative syntax. Writing else if in this form causes a parse error.

Alternative syntax does not change how the condition works. It only makes the boundary between PHP logic and HTML easier to see.

Truthy and falsy values in PHP conditions

An if condition does not have to contain a comparison. PHP converts the evaluated value to a Boolean when necessary.

$items = ["Keyboard", "Mouse"];

if ($items) {
    echo "The cart contains items.";
}

A non-empty array evaluates to true. An empty array evaluates to false.

Common falsy values include:

  • false
  • 0 and 0.0
  • An empty string
  • The string "0"
  • An empty array
  • null

The string "0" is an easy value to overlook. It is valid input in many applications, but it evaluates to false in a Boolean condition.

$quantity = "0";

if ($quantity) {
    echo "Quantity received.";
} else {
    echo "Quantity is missing.";
}

This code reports that the quantity is missing, even though the value exists. Test the exact rule instead:

$quantity = "0";

if ($quantity !== "") {
    echo "Quantity received.";
}

For form fields, identifiers and numeric strings, explicit comparisons are usually safer than relying on truthiness.

Strict and loose comparisons

PHP supports loose comparison with == and strict comparison with ===.

A loose comparison may use PHP type juggling to convert one or both operands before comparing them. A strict comparison requires both the value and type to match.

$submittedValue = "10";

if ($submittedValue == 10) {
    echo "Loose comparison matched.";
}

if ($submittedValue === 10) {
    echo "Strict comparison matched.";
}

The first condition is true because PHP compares the numeric string with the integer after type conversion. The second condition is false because a string is not identical to an integer.

Prefer strict comparisons when you know the expected type. They make conditions easier to reason about and reduce surprises caused by automatic type conversion.

When input arrives through $_GET or $_POST, remember that scalar values normally arrive as strings. Validate or filter the input before comparing it with integers, floats or Boolean values.

$ageInput = $_POST["age"] ?? "";
$age = filter_var($ageInput, FILTER_VALIDATE_INT);

if ($age !== false && $age >= 18) {
    echo "Age requirement satisfied.";
} else {
    echo "Enter a valid age of 18 or above.";
}

The strict check $age !== false matters because 0 is a valid integer result from filter_var(), but it is also falsy.

Nested if statements

An if block can contain another if statement. This is useful when a second check should happen only after the first one succeeds.

$isLoggedIn = true;
$userRole = "editor";

if ($isLoggedIn) {
    if ($userRole === "admin") {
        echo "Open administrator dashboard.";
    } else {
        echo "Open user dashboard.";
    }
}

Nested conditions are valid, but several levels of nesting make code harder to scan. In functions, an early return can often keep the main path flatter.

function getDashboard(string $userRole, bool $isLoggedIn): string
{
    if (!$isLoggedIn) {
        return "login";
    }

    if ($userRole === "admin") {
        return "admin-dashboard";
    }

    return "user-dashboard";
}

This version handles exceptional cases first and avoids wrapping the rest of the function in another block.

Common PHP if else mistakes

Most problems with conditional statements come from a small set of mistakes. They are easy to miss because the code often remains valid PHP.

Using assignment instead of comparison

A single equals sign assigns a value. It does not compare two values.

$status = "pending";

if ($status = "paid") {
    echo "Payment received.";
}

This condition assigns "paid" to $status. The assigned non-empty string evaluates to true, so the message is always displayed.

Use a comparison operator instead:

$status = "pending";

if ($status === "paid") {
    echo "Payment received.";
}

Adding a semicolon after the condition

A semicolon immediately after an if condition creates an empty statement.

$isActive = false;

if ($isActive);
{
    echo "Account is active.";
}

The block is no longer controlled by the if statement, so it runs every time. Remove the semicolon:

$isActive = false;

if ($isActive) {
    echo "Account is active.";
}

Writing conditions in the wrong order

In an elseif chain, PHP stops after the first match. A broad condition placed too early can prevent more specific conditions from running.

$orderTotal = 250;

if ($orderTotal >= 50) {
    $discount = 5;
} elseif ($orderTotal >= 200) {
    $discount = 15;
}

The customer receives only a 5% discount because the first condition already matched. Check the higher threshold first:

$orderTotal = 250;

if ($orderTotal >= 200) {
    $discount = 15;
} elseif ($orderTotal >= 50) {
    $discount = 5;
} else {
    $discount = 0;
}

Using empty() when zero is valid

The empty() function returns true for several values, including 0 and the string "0". That can be a problem when zero is valid input.

$stock = "0";

if (empty($stock)) {
    echo "Stock value was not supplied.";
}

This message is displayed even though the stock value was supplied. Check for the exact invalid value instead:

$stock = "0";

if ($stock === "") {
    echo "Stock value was not supplied.";
} else {
    echo "Current stock: " . (int) $stock;
}

Omitting braces from one-line conditions

PHP permits an if statement without braces when it controls one statement.

if ($isAdmin)
    echo "Administrator";

The syntax is valid, but it becomes fragile when another line is added later.

if ($isAdmin)
    echo "Administrator";
    logAdminAccess();

Only the first line is conditional. logAdminAccess() runs for every user, despite the indentation suggesting otherwise.

Braces make the intended boundary explicit:

if ($isAdmin) {
    echo "Administrator";
    logAdminAccess();
}

When to use if else, switch or match

An if statement is the best general-purpose choice. It works well with ranges, multiple variables and compound expressions.

if ($temperature >= 30 && $isOutdoorEvent) {
    $message = "Provide additional drinking water.";
}

A switch statement can be easier to scan when one value is compared against several fixed cases. However, PHP switch uses loose comparison, which can produce unexpected matches when types differ.

For PHP 8 and later, a match expression is often a cleaner option for mapping one value to one result.

$status = "shipped";

$message = match ($status) {
    "pending" => "Your order is being prepared.",
    "shipped" => "Your order is on the way.",
    "delivered" => "Your order was delivered.",
    default => "Order status is unavailable.",
};

echo $message;

Unlike switch, match uses strict comparison, returns a value and does not require break statements.

Use these guidelines:

  • Use if and elseif for ranges, compound rules and unrelated conditions.
  • Use match when one value must be mapped to a result using strict comparisons.
  • Use switch mainly when maintaining existing code or when its fall-through behaviour is intentionally required.

Use the ternary operator only for small expressions

The ternary operator is a compact form of a simple if else expression.

$isLoggedIn = true;

$message = $isLoggedIn ? "Welcome back." : "Please sign in.";

The equivalent if else statement is:

$isLoggedIn = true;

if ($isLoggedIn) {
    $message = "Welcome back.";
} else {
    $message = "Please sign in.";
}

The ternary form is useful for assigning one of two short values. Use a normal if else block when either branch performs several operations or when the condition needs explanation.

Avoid nesting ternary expressions. Saving a few lines is not helpful when the next developer must decode the statement like a puzzle.

Practical guidelines for readable conditions

Conditional logic is easy to write and surprisingly easy to make unreadable. A few habits keep it manageable.

Name complex conditions

When a condition contains several checks, assign it to a descriptive Boolean variable.

$hasValidAge = $age >= 18;
$hasPermission = $isMember || $isAdministrator;

if ($hasValidAge && $hasPermission) {
    echo "Access granted.";
}

This is easier to understand than placing every comparison inside one long if statement.

Avoid comparing Boolean values unnecessarily

A Boolean variable can be used directly.

if ($isActive) {
    echo "Account is active.";
}

if (!$isBlocked) {
    echo "Account is available.";
}

Writing $isActive === true is valid, but it is usually unnecessary when the variable is already guaranteed to be Boolean.

Keep business rules separate from output

When possible, calculate the result first and render it afterwards.

$shippingMessage = "Standard delivery applies.";

if ($orderTotal >= 100) {
    $shippingMessage = "Free delivery applied.";
}

echo $shippingMessage;

This approach becomes more useful as the application grows. It keeps decision-making separate from HTML generation and makes the logic easier to test.

Use functions for repeated conditions

If the same rule appears in several places, move it into a function instead of copying the condition.

function qualifiesForFreeDelivery(float $orderTotal): bool
{
    return $orderTotal >= 100;
}

if (qualifiesForFreeDelivery(125.50)) {
    echo "Free delivery applied.";
}

A named function documents the rule and gives you one place to change it later.

PHP if else FAQ

Can an if statement exist without else?

Yes. Use if by itself when no action is required for a false condition.

if ($hasError) {
    echo "The request could not be completed.";
}

Can an else statement exist without if?

No. An else block must belong to a preceding if or elseif chain.

Can PHP have several elseif statements?

Yes. A conditional chain may contain multiple elseif blocks. PHP checks them from top to bottom and executes only the first matching block.

What is the difference between elseif and else?

elseif checks another condition. else has no condition and runs only when every earlier condition is false.

Should I use == or === in PHP conditions?

Use === when the value and type should both match. Use == only when type conversion is intentional and its behaviour is clearly understood.

Why does the string “0” fail an if condition?

PHP treats the string "0" as false when converting it to Boolean. Use an explicit comparison such as $value !== "" when "0" is valid input.

Is match a replacement for if else?

Not in every case. A match expression is useful when one value is compared with several fixed values. An if else chain is better for ranges, compound expressions and conditions involving several variables.

Conclusion

PHP if, elseif and else statements control which code runs based on a condition. Their syntax is simple, but reliable conditional logic depends on a few details: order conditions carefully, prefer strict comparisons, handle falsy values deliberately and keep complex rules readable.

For small decisions, a basic if else block is usually enough. As the logic grows, descriptive variables, early returns and small functions help prevent the condition from becoming the part of the code everyone is afraid to touch.

Photo of Vincy, PHP developer
Written by Vincy Last updated: July 28, 2026
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Continue Learning

These related tutorials may help you continue learning.

5 Comments on "PHP If Else Statements: Syntax and Practical Examples"

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore topics
Need PHP help?