PHP If...Else

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 48 of 255

What Is if...else?

In simple terms: if...else chooses between two actions: one when a condition is true, and another when it is false.

Technically: The else clause attaches to an if statement and provides a block that runs when the if condition evaluates to false. Exactly one of the two blocks always runs.

Why It Is Needed

A plain if only describes what happens when a condition is true. Many decisions have two meaningful outcomes:

  • Logged in → show the dashboard; otherwise → show the login form.
  • Payment succeeded → confirm the order; otherwise → show an error.
  • Stock available → enable "Add to cart"; otherwise → show "Notify me".

if...else expresses both outcomes in one structure, so the reader sees the full decision in one place.


Syntax

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

Example: Even or Odd

<?php
$number = 7;

if ($number % 2 === 0) {
    echo "$number is even\n";
} else {
    echo "$number is odd\n";
}

Output

7 is odd

How It Works

  1. $number % 2 is the remainder after dividing by 2, which is 1 for 7.
  2. 1 === 0 is false, so the if block is skipped.
  3. The else block runs.
  4. Execution continues after the closing } of the else block.
         condition?
        /          \
     true          false
       |             |
  [if block]    [else block]
        \          /
     code after if...else

Practical Example: Checking a Password

<?php
$storedHash = password_hash('Secure#2026', PASSWORD_DEFAULT);

$attempts = ['secure#2026', 'Secure#2026'];

foreach ($attempts as $input) {
    if (password_verify($input, $storedHash)) {
        echo "'$input': login successful\n";
    } else {
        echo "'$input': incorrect password\n";
    }
}

Output

'secure#2026': incorrect password
'Secure#2026': login successful

How It Works

  • password_hash() creates a secure, salted hash of the password. Applications store only this hash, never the plain password.
  • password_verify() checks whether an input matches the hash and returns true or false, which makes it a perfect if condition.
  • Passwords are case-sensitive, so the first attempt fails.

Password handling is covered in Password Hashing. (In a real login form, never echo the entered password back to the page.)


Assigning Values in Each Branch

A common use of if...else is to give a variable one of two values.

Example

<?php
$cartTotal = 750;

if ($cartTotal >= 999) {
    $shippingFee = 0;
} else {
    $shippingFee = 79;
}

echo "Shipping: ₹$shippingFee\n";

Output

Shipping: ₹79

Both branches assign $shippingFee, so the variable is guaranteed to exist after the statement.

Alternative: Default Value, Then Override

<?php
$cartTotal = 750;

$shippingFee = 79;

if ($cartTotal >= 999) {
    $shippingFee = 0;
}

echo "Shipping: ₹$shippingFee\n";

This version sets the common case first and changes it only when the condition is true. Both styles are valid; the default-first style is convenient when the else branch would only assign a value.

Alternative: Ternary Operator

When each branch only produces a value, the ternary operator expresses the same decision in one line:

$shippingFee = $cartTotal >= 999 ? 0 : 79;

The ternary operator is covered in PHP Shorthand if. Use if...else when branches contain several statements or when a one-line expression would become hard to read.


if...else Inside Functions

When both branches return, the else keyword is not strictly needed, because return already ends the function:

<?php
function stockLabel(int $quantity): string
{
    if ($quantity > 0) {
        return "In stock ($quantity available)";
    }

    return "Out of stock";
}

echo stockLabel(12) . "\n";
echo stockLabel(0) . "\n";

Output

In stock (12 available)
Out of stock

If $quantity > 0, the function returns immediately; otherwise execution reaches the final return. Leaving out the redundant else reduces nesting, which matters as functions grow. Both forms are correct — choose the one that reads most clearly.


Multiple Statements in Each Branch

Each branch can contain any amount of code:

<?php
$order = ['id' => 9021, 'paid' => false, 'total' => 1450];
$log = [];

if ($order['paid']) {
    $status = 'confirmed';
    $log[] = "Order {$order['id']} confirmed";
    $message = "Thank you! Your order is confirmed.";
} else {
    $status = 'awaiting_payment';
    $log[] = "Order {$order['id']} waiting for payment of ₹{$order['total']}";
    $message = "Please complete the payment to confirm your order.";
}

echo "Status: $status\n";
echo "Message: $message\n";
echo "Log: " . implode('; ', $log) . "\n";

Output

Status: awaiting_payment
Message: Please complete the payment to confirm your order.
Log: Order 9021 waiting for payment of ₹1450

Every variable is set in both branches, so code after the statement can use them safely. If a variable is set in only one branch, it will be undefined in the other case.


if...else in HTML Templates

In templates, the alternative syntax (if:, else:, endif;) keeps the HTML readable:

<?php $user = ['name' => 'Nila', 'unread' => 0]; ?>
<?php if ($user['unread'] > 0): ?>
<p>You have <?= $user['unread'] ?> unread messages.</p>
<?php else: ?>
<p>No new messages, <?= htmlspecialchars($user['name']) ?>.</p>
<?php endif; ?>

Output (HTML)

<p>No new messages, Nila.</p>

See Alternative Syntax for details.


Common Mistakes

Variable Defined in Only One Branch

<?php
$score = 30;

if ($score >= 40) {
    $result = 'Pass';
}

echo $result;

Output

PHP Warning:  Undefined variable $result in /path/script.php on line 8

Fix: Assign the variable in an else branch, or initialize it before the if.

The Dangling else

When braces are omitted, an else belongs to the nearest preceding if, regardless of indentation:

<?php
$isMember = false;
$cartTotal = 1500;

if ($isMember)
    if ($cartTotal > 1000)
        echo "Free gift added\n";
else
    echo "Join our membership to get free gifts\n";

echo "Done\n";

Output

Done

The indentation suggests that the else belongs to if ($isMember), but PHP attaches it to the inner if ($cartTotal > 1000). Because $isMember is false, the entire inner statement — including its else — is skipped, so the membership message never appears.

Fix: Always use braces:

<?php
$isMember = false;
$cartTotal = 1500;

if ($isMember) {
    if ($cartTotal > 1000) {
        echo "Free gift added\n";
    }
} else {
    echo "Join our membership to get free gifts\n";
}

Output

Join our membership to get free gifts

Negative Conditions With else

if (!$isActive) {
    echo "Account inactive";
} else {
    echo "Account active";
}

This forces the reader to resolve "not not active" for the else branch. Prefer the positive condition first:

if ($isActive) {
    echo "Account active";
} else {
    echo "Account inactive";
}

Using if...else for Independent Checks

Effect: Only one branch runs, even when both conditions could be relevant.

Fix: Use separate if statements for independent checks.


Best Practices

  • Always use braces for both the if and the else block.
  • Make sure variables used after the statement are set in every branch (or before the statement).
  • Put the positive or most common case first when it improves readability.
  • Use the ternary operator for simple value choices and if...else for multiple statements.
  • Inside functions, consider returning early instead of using else to reduce nesting.

Official reference: https://www.php.net/manual/en/control-structures.else.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 and get answers drawn from it.

Signed-in readers only.