PHP Relational Operators
In this page:
Equality and Inequality
== checks whether two values are equal *after* PHP converts them to a common type if needed, so "5" == 5 evaluates to true even though one side is a string. != is simply its opposite, flagging values as different once that same type coercion has been applied.
Example: Equality and Inequality
<?php
var_dump("5" == 5);
var_dump(5 != 6);
?>
Login to try C/C++/Java/PHP code in the editor
Strict Equality and Inequality
=== requires both the value *and* the type to match exactly, so "5" === 5 is false — a string can never strictly equal an integer, no matter what it looks like. !== is its inverse. Reaching for the strict versions by default avoids a whole category of subtle type-coercion bugs.
Example: Strict Equality and Inequality
<?php
var_dump("5" === 5);
var_dump("5" !== 5);
?>
Login to try C/C++/Java/PHP code in the editor
Greater Than and Less Than
> and < compare two values by ordinary numeric or string ordering, returning true only when the comparison is strictly one-sided — equal values fail both > and <, which is exactly why the equal-or-greater variants below exist for cases where a tie should count.
Example: Greater Than and Less Than
<?php
var_dump(5 > 3);
var_dump(5 < 5);
?>
Login to try C/C++/Java/PHP code in the editor
Greater Than or Equal to and Less Than or Equal to
>= and <= extend > and < to also accept equality, which is what you want for boundary checks like 'is this age old enough' or 'has this value reached its limit' — situations where the boundary value itself should pass the check, not just values strictly beyond it.
Example: Greater Than or Equal to and Less Than or Equal to
<?php
$age = 18;
var_dump($age >= 18);
var_dump($age <= 17);
?>
Login to try C/C++/Java/PHP code in the editor
Spaceship Operator (<=>)
<=>, the spaceship operator, condenses a three-way comparison into one expression: it returns -1, 0, or 1 depending on whether the left side is smaller, equal, or larger. It exists specifically to simplify writing custom sort comparison functions, where you'd otherwise need three separate if branches.
Example: Spaceship Operator (<=>)
<?php
echo 3 <=> 5, "\n";
echo 5 <=> 5, "\n";
echo 8 <=> 5;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: