PHP If

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

What Is the if Statement? In simple terms: The if statement runs a block of code only when a condition is true. If the condition is false, PHP skips the block and continues with the code after it. Tec

What Is the if Statement?

In simple terms: The if statement runs a block of code only when a condition is true. If the condition is false, PHP skips the block and continues with the code after it.

Technically: if is a control structure that evaluates an expression, converts the result to a boolean, and executes the following statement or block only when the result is true. It is the most fundamental way to control the flow of a program.

Why It Is Needed

Many actions should happen only in certain situations:

  • Show a "low stock" warning only when stock is low.
  • Send a confirmation email only when an order was saved successfully.
  • Apply a discount only when the cart meets a minimum amount.
  • Stop processing a request when required data is missing.

Syntax

if (condition) {
    // code that runs only when condition is true
}
PartMeaning
ifThe keyword that starts the statement
(condition)Any expression; its result is converted to true or false. The parentheses are required.
{ ... }The block of statements that runs when the condition is true

Example

<?php
$temperature = 39;

if ($temperature > 37.5) {
    echo "Fever detected. Please consult a doctor.\n";
}

echo "Reading recorded: {$temperature}°C\n";

Output

Fever detected. Please consult a doctor.
Reading recorded: 39°C

How It Works

  1. PHP evaluates $temperature > 37.5, which is true.
  2. Because the condition is true, the block runs and prints the warning.
  3. Execution continues after the closing }, so the second message is printed regardless of the condition.

With $temperature = 36.8, only the second line would be printed.


What Can Be Used as a Condition?

Any expression can be a condition. PHP converts its value to a boolean.

Comparisons

if ($age >= 18) { ... }
if ($status === 'paid') { ... }

Boolean Variables

<?php
$isVerified = true;

if ($isVerified) {
    echo "Verified account\n";
}

Output

Verified account

A boolean variable is already true or false; writing if ($isVerified === true) adds nothing.

Functions That Return Booleans

<?php
$email = "kavya@gocourse.in";

if (str_ends_with($email, '@gocourse.in')) {
    echo "Staff account\n";
}

if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
    echo "Valid email format\n";
}

Output

Staff account
Valid email format

filter_var() returns the filtered value on success or false on failure, so it is compared strictly with false.

Combined Conditions

<?php
$cartTotal = 1500;
$hasCoupon = true;

if ($cartTotal >= 1000 && $hasCoupon) {
    echo "Coupon applied\n";
}

Output

Coupon applied

Logical operators are explained in Logical Operators, and techniques for writing conditions in PHP If Operators.

Truthiness

When the condition is not a boolean, PHP applies truthiness rules: false, 0, 0.0, "", "0", [], and null are treated as false; everything else as true.

<?php
$notifications = ['New message', 'Order shipped'];

if ($notifications) {
    echo "You have " . count($notifications) . " notifications\n";
}

Output

You have 2 notifications

A non-empty array is truthy. This style is common, but explicit conditions (count($notifications) > 0, $notifications !== []) make intent clearer and avoid surprises such as "0" being false.


Curly Braces and Single Statements

PHP allows omitting the braces when the if controls only one statement:

if ($stock === 0) echo "Out of stock";

This is legal but risky. Adding a second line later creates a bug:

<?php
$stock = 20;

if ($stock === 0)
    echo "Out of stock\n";
    echo "Hidden from search\n";

Output

Hidden from search

Only the first statement belongs to the if. The second line runs always, despite its indentation, because PHP ignores indentation. Always use braces:

<?php
$stock = 20;

if ($stock === 0) {
    echo "Out of stock\n";
    echo "Hidden from search\n";
}

This prints nothing, as intended.


The Stray Semicolon Bug

<?php
$stock = 50;

if ($stock < 10); {
    echo "Low stock!\n";
}

Output

Low stock!

Why This Happens

The semicolon right after ) ends the if statement with an empty statement. The { ... } that follows is not part of the if — it is an ordinary standalone block that always runs. PHP reports no error, which makes this bug hard to see. Never put a semicolon between the condition and the block.


Several Independent if Statements

When conditions are independent — more than one may apply at the same time — use separate if statements rather than an elseif chain.

Example: Assigning Badges

<?php
$user = ['orders' => 12, 'reviews' => 3, 'member_since' => 2019];
$badges = [];

if ($user['orders'] >= 10) {
    $badges[] = 'Loyal Customer';
}

if ($user['reviews'] >= 5) {
    $badges[] = 'Top Reviewer';
}

if ($user['member_since'] <= 2020) {
    $badges[] = 'Early Member';
}

echo $badges ? implode(', ', $badges) : 'No badges yet';

Output

Loyal Customer, Early Member

How It Works

Each if is checked separately. The user qualifies for two badges, so two blocks run. An elseif chain would stop after the first match and award only one badge.

Rule:

  • Use separate if statements when conditions can be true at the same time.
  • Use if...elseif when the cases are mutually exclusive (only one should apply).

Guard Clauses: Using if to Exit Early

A guard clause is an if at the beginning of a function that handles an invalid or special case and returns immediately. It avoids deep nesting and keeps the main logic at the lowest indentation level.

Example: Applying a Coupon

<?php
function couponMessage(float $cartTotal, ?string $code, array $coupons): string
{
    if ($code === null || trim($code) === '') {
        return 'No coupon entered.';
    }

    $code = strtoupper(trim($code));

    if (!isset($coupons[$code])) {
        return "Coupon $code does not exist.";
    }

    $coupon = $coupons[$code];

    if ($cartTotal < $coupon['min_total']) {
        $missing = $coupon['min_total'] - $cartTotal;
        return sprintf('Add ₹%.2f more to use %s.', $missing, $code);
    }

    $discount = $cartTotal * $coupon['percent'] / 100;

    return sprintf('%s applied: you save ₹%.2f.', $code, $discount);
}

$coupons = [
    'WELCOME10' => ['percent' => 10, 'min_total' => 500],
    'FEST25'    => ['percent' => 25, 'min_total' => 2000],
];

echo couponMessage(800, ' welcome10 ', $coupons) . "\n";
echo couponMessage(800, 'FEST25', $coupons) . "\n";
echo couponMessage(800, 'SAVE50', $coupons) . "\n";
echo couponMessage(800, null, $coupons) . "\n";

Output

WELCOME10 applied: you save ₹80.00.
Add ₹1200.00 more to use FEST25.
Coupon SAVE50 does not exist.
No coupon entered.

Step-by-Step Explanation

  1. First guard: if no code was entered (null or only spaces), return a message immediately.
  2. The code is normalized: trimmed and uppercased, so ' welcome10 ' matches 'WELCOME10'.
  3. Second guard: if the code is not a key in $coupons, return an error.
  4. Third guard: if the cart total is below the coupon's minimum, return how much more is needed.
  5. Only when all guards pass does the function reach the main logic: calculating the discount.

Why Guard Clauses Help

The same logic written with nested if...else blocks would indent the success path three levels deep, with each else far away from the condition it belongs to. Guard clauses keep each check next to its consequence and leave the "happy path" at the end, easy to find. Nesting is discussed further in PHP Nested if.


Assigning and Testing in One Condition

An assignment inside a condition stores a value and tests it at the same time. Wrap the assignment in parentheses:

<?php
$text = "Order #4521 confirmed";

if (($pos = strpos($text, '#')) !== false) {
    echo "Order number starts at position $pos\n";
}

Output

Order number starts at position 6

Without the parentheses, !== would be evaluated first, and $pos would receive a boolean. See Assignment Operators.


if in HTML Templates

In files that mix PHP and HTML, the alternative syntax replaces braces with : and endif;, which is easier to read between HTML tags:

<?php $isLoggedIn = true; $name = 'Meena'; ?>
<?php if ($isLoggedIn): ?>
    <p>Welcome back, <?= htmlspecialchars($name) ?>!</p>
<?php endif; ?>

Output (HTML)

    <p>Welcome back, Meena!</p>

The alternative syntax is covered in Alternative Syntax.


Common Mistakes

Assignment Instead of Comparison

if ($role = 'admin') { ... }   // always true

Fix: if ($role === 'admin').

Semicolon After the Condition

Effect: The block always runs.

Fix: Remove the semicolon: if (...) { ... }.

Omitting Braces

Effect: Only the first statement is controlled by the if.

Fix: Always use braces.

Using elseif for Independent Conditions (or Separate ifs for Exclusive Ones)

Effect: Too few or too many blocks run.

Fix: Separate if statements for independent checks; elseif for mutually exclusive cases.

Relying on Loose Truthiness

Effect: "0", 0, and [] are treated as "missing".

Fix: Write explicit conditions such as $value !== '' or $count > 0.

Reading Array Keys That May Not Exist

Effect: if ($_GET['debug']) raises "Undefined array key" when the parameter is absent.

Fix: if (($_GET['debug'] ?? '') === '1') or isset() first.


Best Practices

  • Always use curly braces, even for one statement.
  • Prefer explicit conditions with strict comparison (===, !==).
  • Use guard clauses to handle invalid cases early and keep the main logic unindented.
  • Store complex conditions in well-named boolean variables before the if.
  • Choose between independent if statements and elseif chains deliberately.

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

Signed-in readers only.