← Back to PHP Course | Chapter 3: Operators | Lesson 2 of 8

PHP Relational Operators

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
<?php
var_dump("5" == 5);
var_dump(5 != 6);
?>

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
<?php
var_dump("5" === 5);
var_dump("5" !== 5);
?>

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
<?php
var_dump(5 > 3);
var_dump(5 < 5);
?>

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
<?php
$age = 18;
var_dump($age >= 18);
var_dump($age <= 17);
?>

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
<?php
echo 3 <=> 5, "\n";
echo 5 <=> 5, "\n";
echo 8 <=> 5;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.