Comparison Operators

Ma Mahalakshmi V Updated 14 Nov 2026
9 min read ·Lesson 39 of 255

What Are Comparison Operators?

In simple terms: Comparison operators compare two values and answer a yes/no question: Are they equal? Is one larger than the other?

Technically: A comparison operator takes two operands and returns a boolean (true or false). The only exception is the spaceship operator <=>, which returns an integer. Comparisons are the foundation of every if statement, loop condition, filter, and sort.


The Comparison Operators

OperatorNametrue When
$a == $bEqual$a equals $b after type juggling
$a === $bIdentical$a equals $b and they have the same type
$a != $bNot equalNot equal after type juggling
$a <> $bNot equalSame as !=
$a !== $bNot identicalDifferent values or different types
$a < $bLess than$a is less than $b
$a > $bGreater than$a is greater than $b
$a <= $bLess than or equal$a is less than or equal to $b
$a >= $bGreater than or equal$a is greater than or equal to $b
$a <=> $bSpaceshipReturns -1, 0, or 1 (see Spaceship Operator)

Example

<?php
$stock = 12;
$minimum = 10;

var_dump($stock == 12);
var_dump($stock === "12");
var_dump($stock != $minimum);
var_dump($stock > $minimum);
var_dump($stock <= 5);

Output

bool(true)
bool(false)
bool(true)
bool(true)
bool(false)

Equality: == vs ===

This is the most important distinction among the comparison operators.

== — Loose Equality

== converts the operands to a common type before comparing. The conversion rules are described in detail in PHP Type Juggling.

=== — Strict Equality

=== compares without conversion. Both the type and the value must match.

Example

<?php
$pairs = [
    [5, "5"],
    [0, false],
    ["1", "01"],
    [null, ""],
    ["abc", "ABC"],
    [1.0, 1],
];

foreach ($pairs as [$a, $b]) {
    printf(
        "%-6s vs %-6s  ==: %-5s ===: %s\n",
        var_export($a, true),
        var_export($b, true),
        var_export($a == $b, true),
        var_export($a === $b, true)
    );
}

Output

5      vs '5'     ==: true  ===: false
0      vs false   ==: true  ===: false
'1'    vs '01'    ==: true  ===: false
NULL   vs ''      ==: true  ===: false
'abc'  vs 'ABC'   ==: false ===: false
1.0    vs 1       ==: true  ===: false

Why === Is the Safer Default

  • === never converts, so its result is predictable from the values alone.
  • Loose comparison treats different strings as equal when they look numeric ("1" == "01"), and treats null, "", 0, and false as interchangeable in many combinations.
  • Even 1.0 === 1 is false, because a float and an int are different types. When you compare numbers of mixed types, convert them first or compare with == deliberately.

Rule: use === and !== by default. Use == only when you intentionally want type conversion — for example, comparing a numeric string from a form with an integer whose type you have not normalized.


Ordering Operators: <, >, <=, >=

Numbers

<?php
$score = 72;

var_dump($score >= 40);
var_dump($score > 90);
var_dump($score >= 40 && $score <= 100);

Output

bool(true)
bool(false)
bool(true)

PHP has no "between" operator. Checking a range combines two comparisons with &&. Remember that <= includes the boundary and < does not — mixing them up causes classic off-by-one errors (for example, whether a score of exactly 40 passes).

Strings

Non-numeric strings are compared character by character using their byte values:

<?php
var_dump("apple" < "banana");
var_dump("Zebra" < "apple");
var_dump("apple" < "Apple");
var_dump("10" < "9");
var_dump("10" < "9a");

Output

bool(true)
bool(true)
bool(false)
bool(false)
bool(true)

Understanding the Results

  • "apple" < "banana" — a comes before b.
  • "Zebra" < "apple" — uppercase letters have lower byte values than lowercase ones (Z is 90, a is 97), so all uppercase words sort before lowercase words.
  • "apple" < "Apple" is false for the same reason.
  • "10" < "9" — both strings are numeric, so PHP compares them as numbers: 10 is not less than 9.
  • "10" < "9a" — "9a" is not numeric, so PHP compares them as strings: "1" comes before "9".

For human-friendly ordering, use strcasecmp() (case-insensitive) or strnatcmp() / strnatcasecmp() (natural order, treating embedded numbers as numbers). For locale-aware sorting of names in languages other than English, use the Collator class from the intl extension.

Version Strings

<?php
var_dump("8.2.10" < "8.10.1");
var_dump(version_compare("8.2.10", "8.10.1", "<"));
var_dump(version_compare(PHP_VERSION, "8.2.0", ">="));

Output (the last line depends on your PHP version)

bool(false)
bool(true)
bool(true)

Plain string comparison sees "8.2" vs "8.1" and decides that "8.2.10" is larger, which is wrong for versions. version_compare() understands version numbers and gives the correct answer.


Comparing Other Types

Booleans and Null

When a boolean or null is compared with another value using ==, <, or >, both sides are converted to booleans:

<?php
var_dump(null == false);
var_dump(null < -1);
var_dump(true > 10);

Output

bool(true)
bool(true)
bool(false)

null < -1 is true because null becomes false, -1 becomes true, and false < true. true > 10 is false because both sides become true. These comparisons are legal but rarely meaningful — check for null explicitly with === null instead.

Arrays

<?php
var_dump([1, 2, 3] < [1, 2, 4]);
var_dump([1, 2] < [1, 2, 3]);
var_dump(['a' => 1, 'b' => 2] == ['b' => 2, 'a' => 1]);
var_dump(['a' => 1, 'b' => 2] === ['b' => 2, 'a' => 1]);

Output

bool(true)
bool(true)
bool(true)
bool(false)
  • An array with fewer elements is considered smaller.
  • Arrays of equal size are compared element by element, by key.
  • == ignores order; === requires the same order and types.

Objects

<?php
$a = new DateTime('2026-10-08 10:00');
$b = new DateTime('2026-10-08 10:00');
$c = $a;

var_dump($a == $b);
var_dump($a === $b);
var_dump($a === $c);

Output

bool(true)
bool(false)
bool(true)
  • == checks whether two objects are of the same class with equal property values.
  • === checks whether both variables refer to the same object instance. $c = $a copies the handle, so $a === $c is true.

Object comparison is covered in Comparing Objects.

Dates

DateTime and DateTimeImmutable objects can be compared directly with <, >, and ==:

<?php
$today = new DateTimeImmutable('2026-10-08');
$deadline = new DateTimeImmutable('2026-12-25');

if ($today < $deadline) {
    $daysLeft = $today->diff($deadline)->days;
    echo "Days until deadline: $daysLeft\n";
}

Output

Days until deadline: 78

Comparing date strings works only for the YYYY-MM-DD format (because it sorts like a number). Formats such as 25/12/2026 compare incorrectly as strings, so convert them to date objects first.


Floats

Floating-point values are approximations, so exact equality is unreliable:

<?php
var_dump(0.1 + 0.2 == 0.3);
var_dump(abs((0.1 + 0.2) - 0.3) < 0.000001);

Output

bool(false)
bool(true)

Compare floats with a tolerance, or round to a known precision before comparing. See PHP Floats.


Comparisons Return Booleans

Because every comparison produces true or false, the result can be stored, returned, or combined:

<?php
function isEligibleForFreeShipping(float $cartTotal, string $pincode): bool
{
    return $cartTotal >= 999 && str_starts_with($pincode, '600');
}

var_dump(isEligibleForFreeShipping(1250, '600042'));
var_dump(isEligibleForFreeShipping(1250, '560001'));

Output

bool(true)
bool(false)

Returning the comparison directly is cleaner than writing if (...) { return true; } else { return false; }.


Spaceship <=>

Returns -1, 0, or 1 and is mainly used for sorting:

<?php
var_dump(3 <=> 5, 5 <=> 5, 7 <=> 5);

Output

int(-1)
int(0)
int(1)

Covered in Spaceship Operator.

Null Coalescing ??

Returns the left operand unless it is null or undefined. Covered in Null Coalescing Operator.

Ternary ?:

Chooses between two values based on a condition. Covered in PHP Shorthand if.


Practical Example: Validating a Booking Request

<?php
function validateBooking(array $booking, DateTimeImmutable $today): array
{
    $errors = [];

    $guests = filter_var($booking['guests'] ?? null, FILTER_VALIDATE_INT);

    if ($guests === false || $guests < 1 || $guests > 6) {
        $errors[] = 'Guests must be between 1 and 6.';
    }

    $checkIn = DateTimeImmutable::createFromFormat('!Y-m-d', $booking['check_in'] ?? '');
    $checkOut = DateTimeImmutable::createFromFormat('!Y-m-d', $booking['check_out'] ?? '');

    if ($checkIn === false || $checkOut === false) {
        $errors[] = 'Dates must use the YYYY-MM-DD format.';
    } else {
        if ($checkIn < $today) {
            $errors[] = 'Check-in cannot be in the past.';
        }

        if ($checkOut <= $checkIn) {
            $errors[] = 'Check-out must be after check-in.';
        }
    }

    if (($booking['room'] ?? '') !== 'deluxe' && ($booking['room'] ?? '') !== 'standard') {
        $errors[] = 'Room must be "standard" or "deluxe".';
    }

    return $errors;
}

$today = new DateTimeImmutable('2026-10-08');

$requests = [
    ['guests' => '2', 'check_in' => '2026-10-20', 'check_out' => '2026-10-23', 'room' => 'deluxe'],
    ['guests' => '9', 'check_in' => '2026-10-01', 'check_out' => '2026-10-01', 'room' => 'suite'],
];

foreach ($requests as $index => $request) {
    $errors = validateBooking($request, $today);
    echo "Request " . ($index + 1) . ": " . ($errors === [] ? 'valid' : implode(' ', $errors)) . "\n";
}

Output

Request 1: valid
Request 2: Guests must be between 1 and 6. Check-in cannot be in the past. Check-out must be after check-in. Room must be "standard" or "deluxe".

Step-by-Step Explanation

  1. Guests: filter_var() converts '2' to int(2) or returns false. The checks === false, < 1, and > 6 reject invalid values; strict comparison with false matters because 0 would also be falsy.
  2. Dates: createFromFormat('!Y-m-d', ...) parses the string strictly. The ! resets the time to midnight, so comparisons are between whole days. Date objects are compared with < and <=.
  3. Check-out: <= rejects stays where check-out is on or before check-in; < would wrongly allow zero-night bookings.
  4. Room: !== checks for exact allowed values. (With more options, in_array($room, $allowed, true) is cleaner.)
  5. $errors === [] checks for an empty array strictly.

Common Mistakes

Using == for Strings That Look Like Numbers

Effect: "0042" == "42" and "1e3" == "1000" are true.

Fix: Use ===.

Comparing Floats Exactly

Effect: Calculated values that "should" be equal are not.

Fix: Compare with a tolerance or after rounding.

Comparing Versions or Formatted Dates as Strings

Effect: "8.2.10" < "8.10.1" is false; "25/12/2026" < "01/01/2027" is false.

Fix: Use version_compare() and date objects.

Off-by-One Boundaries

Effect: A value exactly at the limit is accepted or rejected unexpectedly.

Fix: Decide whether each boundary is inclusive (<=, >=) or exclusive (<, >), and test the boundary values.

Expecting Case-Insensitive String Comparison

Effect: "Admin" === "admin" is false.

Fix: Normalize case (strtolower() / mb_strtolower()) or use strcasecmp().

Using == to Compare With true, false, or null

Effect: Many unrelated values match.

Fix: Use === true, === false, === null, or use the boolean directly in the condition.


Best Practices

  • Use === and !== by default.
  • Normalize types before comparing input (validate and convert with filter_var()).
  • Use dedicated functions for special comparisons: version_compare(), strcasecmp(), strnatcmp(), hash_equals() for secrets.
  • Compare dates as DateTimeImmutable objects, not formatted strings.
  • Return comparison results directly from functions that answer yes/no questions.
  • Test boundary values whenever you write range checks.

Official reference: https://www.php.net/manual/en/language.operators.comparison.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 Comparison Operators and get answers drawn from it.

Signed-in readers only.