PHP If...Else...Elseif

Su Subhalakshmi Chandran Updated 17 Oct 2026
7 min read ·Lesson 30 of 102
In this post

What Are Conditional Statements? In simple terms: Conditional statements let a program make decisions. They run different code depending on whether a condition is true or false — for example, showing

What Are Conditional Statements?

In simple terms: Conditional statements let a program make decisions. They run different code depending on whether a condition is true or false — for example, showing "Welcome back" to logged-in users and a login button to everyone else.

Technically: A conditional statement evaluates an expression, converts the result to a boolean, and chooses which block of code to execute. Code that is not chosen is skipped entirely.

Why They Matter

Without conditions, a program would do the same thing every time. Every real application depends on decisions:

  • Is the user logged in? Do they have permission?
  • Is the form input valid?
  • Is the item in stock? Does the order qualify for free shipping?
  • Did the payment succeed or fail?

Conditional Statements in PHP

StatementUse When
ifRun code only when a condition is true
if...elseChoose between two paths
if...elseif...elseChoose between several paths, checked in order
switchCompare one value against many possible values (loose comparison)
matchReturn a value based on one value, with strict comparison (PHP 8.0+)
Ternary ?:Choose between two values in a single expression
Null coalescing ??Provide a fallback for a missing or null value

This lesson gives an overview of the if family and how the forms relate. Each form is covered in depth in its own lesson: PHP If, PHP If...Else, PHP Shorthand if, PHP Nested if, PHP Switch, and PHP Match.


if — Run Code When a Condition Is True

Syntax

if (condition) {
    // runs only when condition is true
}

Example

<?php
$stock = 3;

if ($stock < 5) {
    echo "Only $stock left — order soon!\n";
}

echo "Product page loaded.\n";

Output

Only 3 left — order soon!
Product page loaded.

The message inside the block appears only because $stock < 5 is true. The last line runs in every case, because it is outside the if.


if...else — Choose Between Two Paths

Syntax

if (condition) {
    // runs when condition is true
} else {
    // runs when condition is false
}

Example

<?php
$isLoggedIn = false;

if ($isLoggedIn) {
    echo "Welcome back!\n";
} else {
    echo "Please log in to continue.\n";
}

Output

Please log in to continue.

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


if...elseif...else — Choose Between Several Paths

Syntax

if (condition1) {
    // runs when condition1 is true
} elseif (condition2) {
    // runs when condition1 is false and condition2 is true
} elseif (condition3) {
    // runs when the earlier conditions are false and condition3 is true
} else {
    // runs when none of the conditions are true
}

Example: Grade Calculator

<?php
function grade(int $score): string
{
    if ($score >= 90) {
        return 'A';
    } elseif ($score >= 75) {
        return 'B';
    } elseif ($score >= 60) {
        return 'C';
    } elseif ($score >= 40) {
        return 'D';
    } else {
        return 'F';
    }
}

foreach ([95, 82, 67, 45, 30] as $score) {
    echo "$score => " . grade($score) . "\n";
}

Output

95 => A
82 => B
67 => C
45 => D
30 => F

How PHP Evaluates the Chain

  1. Conditions are checked from top to bottom.
  2. The first condition that is true runs its block, and the rest of the chain is skipped.
  3. If no condition is true, the else block runs (if there is one).

For a score of 82:

82 >= 90 ?  false → check next
82 >= 75 ?  true  → return 'B'  (remaining conditions are never checked)

Why Order Matters

Because only the first true condition is used, conditions must go from the most specific to the least specific. Reversing the order breaks the logic:

<?php
$score = 95;

if ($score >= 40) {
    echo "D\n";
} elseif ($score >= 90) {
    echo "A\n";
}

Output

D

95 >= 40 is true, so the chain stops immediately, and the A branch is unreachable for every score. With a "greater than or equal" chain, start with the highest threshold.


Visualizing the Flow

           ┌─────────────────┐
           │  condition 1 ?  │
           └───────┬─────────┘
            true   │   false
      ┌────────────┘     └────────────┐
      ▼                               ▼
 [ block 1 ]                ┌─────────────────┐
      │                     │  condition 2 ?  │
      │                     └───────┬─────────┘
      │                      true   │   false
      │                ┌────────────┘     └──────────┐
      │                ▼                             ▼
      │           [ block 2 ]                  [ else block ]
      │                │                             │
      └────────────────┴──────────────┬──────────────┘
                                      ▼
                           code after the statement

Whichever path is taken, execution continues with the code after the entire if statement.


elseif vs else if

PHP accepts both spellings when you use curly braces:

<?php
$temperature = 28;

if ($temperature > 35) {
    echo "Hot\n";
} elseif ($temperature > 25) {
    echo "Warm\n";
} else if ($temperature > 15) {
    echo "Mild\n";
} else {
    echo "Cool\n";
}

Output

Warm
  • elseif is a single keyword.
  • else if is technically an else whose body is a new if statement. With braces, both behave identically.

With the alternative syntax used in templates (if: ... endif;), only elseif works; else if: is a parse error. For consistency, use elseif everywhere — it is also what coding standards such as PER Coding Style recommend.


The Same Decision in Different Forms

Different conditional forms suit different situations. Here is one decision — a shipping label based on cart total — written three ways.

<?php
$cartTotal = 1200;

// 1. if...elseif...else
if ($cartTotal >= 2000) {
    $shipping = 'Free express shipping';
} elseif ($cartTotal >= 999) {
    $shipping = 'Free standard shipping';
} else {
    $shipping = '₹79 shipping';
}
echo $shipping . "\n";

// 2. match (true) — returns a value, PHP 8.0+
$shipping = match (true) {
    $cartTotal >= 2000 => 'Free express shipping',
    $cartTotal >= 999 => 'Free standard shipping',
    default => '₹79 shipping',
};
echo $shipping . "\n";

// 3. Ternary — only suitable for two outcomes
$shipping = $cartTotal >= 999 ? 'Free shipping' : '₹79 shipping';
echo $shipping . "\n";

Output

Free standard shipping
Free standard shipping
Free shipping

The ternary version can express only two outcomes, so it cannot distinguish express shipping; it is shown to illustrate where each form fits.

Choosing a Form

SituationBest Choice
Run extra code only in one caseif
Two different actionsif...else
Several ranges or unrelated conditions, possibly with multiple statements per branchif...elseif...else
Assign one of several values based on conditionsmatch (true)
Compare one value against a list of exact valuesmatch (or switch for multiple statements)
Choose between two short valuesTernary ?:
Default for a missing/null value??

Conditions Are Converted to Boolean

The condition can be any expression. PHP converts its result to true or false using truthiness rules: 0, 0.0, "", "0", [], and null are false; almost everything else is true.

<?php
$cartItems = [];
$couponCode = "0";

if ($cartItems) {
    echo "Cart has items\n";
} else {
    echo "Cart is empty\n";
}

if ($couponCode) {
    echo "Coupon entered\n";
} else {
    echo "No coupon\n";
}

Output

Cart is empty
No coupon

The second result is a bug if "0" is a valid coupon code: the string "0" is falsy. Explicit conditions avoid this — if ($couponCode !== ''). Writing precise conditions is covered in PHP If Operators.


Common Mistakes

Wrong Order in an elseif Chain

Effect: Later branches are unreachable.

Fix: Order conditions from most specific to least specific (for example, highest threshold first).

Using = Instead of ===

Effect: if ($status = 'paid') assigns and is always true.

Fix: Use ===.

Separate if Statements Where elseif Was Intended

<?php
$score = 95;

if ($score >= 90) { echo "A\n"; }
if ($score >= 75) { echo "B\n"; }

Output

A
B

Independent if statements are all checked, so several can run. Use elseif when the cases are mutually exclusive.

Relying on Truthiness for Strings and Numbers

Effect: "0" and 0 are treated as "nothing".

Fix: Compare explicitly: !== '', !== null, > 0.

Forgetting the Final else

Effect: No branch runs for unexpected values, leaving variables undefined.

Fix: Add an else (or initialize the variable before the chain) to handle every remaining case.


Best Practices

  • Always use curly braces, even for single-line blocks.
  • Use elseif (one word) consistently.
  • Order elseif conditions carefully and include an else for unexpected cases.
  • Prefer match (true) when every branch only assigns or returns a value.
  • Keep conditions explicit; extract complex conditions into well-named variables or functions.

Official reference: https://www.php.net/manual/en/control-structures.elseif.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting
Ask about this post
AI Ask about this post

Ask questions about PHP If...Else...Elseif and get answers drawn from it.

Signed-in readers only.