Comparison Operators
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 t
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
| Operator | Name | true When |
|---|---|---|
$a == $b | Equal | $a equals $b after type juggling |
$a === $b | Identical | $a equals $b and they have the same type |
$a != $b | Not equal | Not equal after type juggling |
$a <> $b | Not equal | Same as != |
$a !== $b | Not identical | Different values or different types |
$a < $b | Less than | $a is less than $b |
$a > $b | Greater than | $a is greater than $b |
$a <= $b | Less than or equal | $a is less than or equal to $b |
$a >= $b | Greater than or equal | $a is greater than or equal to $b |
$a <=> $b | Spaceship | Returns -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 treatsnull,"",0, andfalseas interchangeable in many combinations. - Even
1.0 === 1isfalse, 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"—acomes beforeb."Zebra" < "apple"— uppercase letters have lower byte values than lowercase ones (Zis 90,ais 97), so all uppercase words sort before lowercase words."apple" < "Apple"isfalsefor 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 = $acopies the handle, so$a === $cistrue.
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; }.
Related Comparison Operators
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
- Guests:
filter_var()converts'2'toint(2)or returnsfalse. The checks=== false,< 1, and> 6reject invalid values; strict comparison withfalsematters because0would also be falsy. - 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<=. - Check-out:
<=rejects stays where check-out is on or before check-in;<would wrongly allow zero-night bookings. - Room:
!==checks for exact allowed values. (With more options,in_array($room, $allowed, true)is cleaner.) $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
DateTimeImmutableobjects, 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