PHP If

Ma Mahalakshmi V Updated 14 Nov 2026
8 min read ·Lesson 46 of 255

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 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 and get answers drawn from it.

Signed-in readers only.