HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Comparison Operators

Comparison operators are used to compare two values (number or string). These operators are the backbone of logical decision-making in PHP—they always return a Boolean result (TRUE or FALSE).


Table of Comparison Operators

The following table lists the comparison operators supported by PHP:

Operator Name Description
== Equal Returns true if $x is equal to $y
=== Identical Returns true if $x is equal to $y, **and they are of the same type**
!= Not equal Returns true if $x is not equal to $y
!== Not identical Returns true if $x is not equal to $y, or they are not of the same type
> Greater than Returns true if $x is greater than $y
< Less than Returns true if $x is less than $y
>= Greater than or equal to Returns true if $x is greater than or equal to $y
<= Less than or equal to Returns true if $x is less than or equal to $y
<=> Spaceship Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y.

Equal (==) vs. Identical (===)

This is one of the most important concepts for PHP developers to master. While == only checks the value, === checks both the value and the data type.

<?php
    $x = 100;  
    $y = "100";

    var_dump($x == $y);  // bool(true) - because values are equal
    var_dump($x === $y); // bool(false) - because types are different (int vs string)
?>

The Spaceship Operator (<=>)

Introduced in PHP 7, the spaceship operator is used for comparing two expressions. It returns:

  • -1 if the left side is smaller than the right.
  • 0 if both sides are equal.
  • 1 if the left side is larger than the right.
<?php
    echo 5 <=> 10; // Outputs: -1
    echo 10 <=> 10; // Outputs: 0
    echo 10 <=> 5; // Outputs: 1
?>
Note: Comparison operators don't just work on numbers; you can also use them to compare strings alphabetically.
Pro Tip: Always prefer using === over ==. Strict comparison prevents "weird" PHP behavior where strings might be unexpectedly converted to numbers.

Key Points to Remember

  • Comparison operators always return a Boolean (True/False).
  • Use === to check both value and data type for better security.
  • != and <> are identical (both mean "not equal").
  • The Spaceship operator is great for custom sorting logic.
  • PHP can compare different data types, but you should be aware of type juggling rules.