PHP If...Else...Elseif

Ma Mahalakshmi V Updated 14 Nov 2026
7 min read ·Lesson 45 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
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.