if...else Statements

Run different code depending on whether a condition is true.

Syntaxif (condition) { // code } elseif (condition) { // code } else { // code }

Conditional statements let your script make decisions.

  • if — run a block if a condition is true.
  • if...else — run one block or another.
  • if...elseif...else — test several conditions in order.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Redirect unauthenticated users to the login page only when the session contains no user ID.
  • Display a different discount message based on whether a customer's cart total exceeds a threshold.
  • Show a 'Your account is suspended' banner when a user's status flag equals 'banned'.

More examples

Basic if / else

The simplest branch: one path when the condition is true, another when it is false.

Example · php
<?php
$balance = 120;

if ($balance >= 100) {
    echo 'Premium tier';
} else {
    echo 'Standard tier';
}

if / elseif / else chain

elseif chains test conditions in order; the first true branch runs and the rest are skipped.

Example · php
<?php
$score = 74;

if ($score >= 90) {
    echo 'A';
} elseif ($score >= 75) {
    echo 'B';
} elseif ($score >= 60) {
    echo 'C';
} else {
    echo 'F';
}

Nested if for multi-factor checks

Nested ifs separate independent conditions, here distinguishing authentication from authorisation.

Example · php
<?php
$isLoggedIn = true;
$isAdmin    = false;

if ($isLoggedIn) {
    if ($isAdmin) {
        echo 'Admin dashboard';
    } else {
        echo 'User dashboard';
    }
} else {
    header('Location: /login');
    exit;
}

Discussion

  • Be the first to comment on this lesson.