A comparison operator asks a question about two values and answers with true or false. You will use these in every if statement.
| Operator | Meaning | Example |
|---|---|---|
== | Equal (after type conversion) | 5 == "5" is true |
=== | Identical (same value and type) | 5 === "5" is false |
!= or <> | Not equal | 5 != 6 is true |
!== | Not identical | 5 !== "5" is true |
> | Greater than | 7 > 3 is true |
< | Less than | 7 < 3 is false |
>= | Greater than or equal | 7 >= 7 is true |
<= | Less than or equal | 3 <= 2 is false |
<=> | Spaceship (compare and return -1, 0 or 1) | 3 <=> 7 is -1 |
<?php
var_dump(5 > 3);
var_dump(5 <= 3);
var_dump(5 == "5");
var_dump(5 === "5");
bool(true)
bool(false)
bool(true)
bool(false)
Comparing text
Strings are compared character by character. Capital letters come before small letters.
<?php
var_dump("apple" < "banana");
var_dump("Zebra" < "apple");
var_dump("hello" === "Hello");
bool(true)
bool(true)
bool(false)
The spaceship operator
<=> returns -1 if the left side is smaller, 0 if they are equal and 1 if the left side is bigger. It is the standard tool for sorting.
<?php
echo (3 <=> 7) . "\n";
echo (5 <=> 5) . "\n";
echo (9 <=> 2);
-1
0
1
Use it for sorting
<?php
$people = [
["name" => "Zoya", "age" => 30],
["name" => "Ali", "age" => 22],
["name" => "Mira", "age" => 27],
];
usort($people, fn($a, $b) => $a["age"] <=> $b["age"]);
foreach ($people as $p) {
echo $p["name"] . " ";
}
Ali Mira Zoya
Prefer ===
=== and !== by default. Reach for == only when you really want type conversion. The next lesson shows why.