Comparison Operators

Compare two values and get a boolean result.

Comparison operators return true or false.

OperatorMeaning
==Equal (value)
===Identical (value and type)
!=Not equal
< >Less / greater than
<=>Spaceship (-1, 0 or 1)

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Use === to compare a user-submitted form value against an expected type-safe string.
  • Compare a product's stock level to zero with > to decide whether to show the 'In Stock' badge.
  • Validate that a submitted age falls between 18 and 120 using >= and <= in a registration form.

More examples

Loose vs strict equality

=== checks both value and type, eliminating the surprising loose comparisons that catch many beginners off-guard.

Example · php
<?php
$input = '0';  // string from a form

var_dump($input == false);   // true  (loose — '0' is falsy)
var_dump($input === false);  // false (strict — different types)
var_dump($input === '0');    // true

Relational comparisons

>, <, >=, and <= compare numeric or string magnitudes, combining cleanly with logical operators for range checks.

Example · php
<?php
$stock = 5;
$minOrder = 1;
$maxOrder = 10;

if ($stock > 0 && $minOrder >= 1 && $minOrder <= $maxOrder) {
    echo 'Order accepted';
}

Spaceship operator for sorting

The spaceship operator <=> returns -1, 0, or 1, making it the concise comparator callback for usort().

Example · php
<?php
$products = [
    ['name' => 'Widget', 'price' => 9.99],
    ['name' => 'Gadget', 'price' => 4.49],
    ['name' => 'Doohickey', 'price' => 14.0],
];

usort($products, fn($a, $b) => $a['price'] <=> $b['price']);

foreach ($products as $p) {
    echo "{$p['name']}: {$p['price']}\n";
}

Discussion

  • Be the first to comment on this lesson.