PHP Comparison Operators
Comparison operators compare two values and return a boolean result (true or false). They're essential for making decisions in your code. Understanding the difference between loose and strict comparison is crucial!
Comparison Operators Overview
| Operator | Name | Example | Result |
|---|---|---|---|
== |
Equal | 5 == "5" |
true (loose) |
=== |
Identical | 5 === "5" |
false (strict) |
!= |
Not equal | 5 != 3 |
true |
<> |
Not equal | 5 <> 3 |
true |
!== |
Not identical | 5 !== "5" |
true |
< |
Less than | 3 < 5 |
true |
> |
Greater than | 5 > 3 |
true |
<= |
Less than or equal | 5 <= 5 |
true |
>= |
Greater than or equal | 5 >= 3 |
true |
<=> |
Spaceship | 5 <=> 3 |
1 |
Output
Click Run to execute your code
Loose vs Strict Comparison
Key Difference:
- Loose (==, !=): Compares values after type juggling
- Strict (===, !==): Compares both value AND type
<?php
$a = 5;
$b = "5";
// Loose comparison
var_dump($a == $b); // true (values are equal after conversion)
// Strict comparison
var_dump($a === $b); // false (different types: int vs string)
?>
Spaceship Operator (<=>) - PHP 7+
Returns -1, 0, or 1 based on comparison. Perfect for sorting!
<?php
echo 5 <=> 3; // 1 (5 is greater)
echo 3 <=> 5; // -1 (3 is less)
echo 5 <=> 5; // 0 (equal)
// Useful for sorting
usort($array, function($a, $b) {
return $a <=> $b; // Ascending sort
});
?>
Common Mistakes
Using == instead of ===
<?php
if ($value == 0) { // โ Dangerous!
// Executes for: 0, "0", "", false, null, []
}
if ($value === 0) { // โ
Better
// Only executes for integer 0
}
?>
Summary
- ==: Loose equality (type juggling)
- ===: Strict equality (type + value)
- !=, <>: Not equal (loose)
- !==: Not identical (strict)
- <=>: Spaceship (-1, 0, 1)
- Best Practice: Use === and !== by default
What's Next?
Next, we'll explore Logical Operators - combining multiple conditions with AND, OR, and NOT!
Enjoying these tutorials?