Comparison Operators in PHP: A Comprehensive Guide


In PHP, comparison operators are used to compare two values and determine their relationship or equality. These operators evaluate expressions and return a Boolean result, either true or false, based on the comparison's outcome.

Here are the comparison operators available in PHP:

Equal (==): It checks if two values are equal, disregarding their data types. For example:

<?php
    $a=45;
    $b="45";
    var_dump($a==$b);
?>

Identical (===): It checks if two values are equal and have the same data type. For example:

<?php
    $a=45;
    $b=45;
    var_dump($a===$b);
?>

Not equal (!= or <>): It checks if two values are not equal, irrespective of their data types. For example:

<?php
   $a=45;
   $b=35;
   var_dump($a!=$b);
   var_dump($a<>$b);
?>

Not identical (!==): It checks if two values are not equal or do not have the same data type. For example:

<?php
   $a=45;
   $b="45";
   var_dump($a!==$b);
?>

Greater than (>): It checks if the left operand is greater than the right operand. For example:

<?php
    $age=25;
    var_dump($age>18);
?>

Less than (<) : It checks if the left operand is less than the right operand. For example:

<?php
    $a=45;
    $b=45;
    var_dump($a<$b);
?>

Greater than or equal to (>=): It checks if the left operand is greater than or equal to the right operand. For example:

<?php
    $age=25;
    var_dump($age>18);
    //Greater than or equal to    
    var_dump($age>=18);
?>

Less than or equal to(<=) : It checks if the left operand is less than or equal to the right operand. For example:

<?php
    $a=45;
    $b=45;
    var_dump($a<$b);
    //Less than or equal to    
    var_dump($a<=$b);
?>

spaceship operator

The spaceship operator, also known as the combined comparison operator, is a unique operator introduced in PHP 7. It is represented by the symbol <=>. The spaceship operator is used to compare two expressions and returns an integer value based on the comparison result.

Here's how the spaceship operator works:

  • If the left-hand side (LHS) expression is less than the right-hand side (RHS) expression, it returns -1.0
  • If the LHS expression is greater than the RHS expression, it returns 1.
  • If both expressions are equal, it returns 0.

Here's an example to demonstrate the usage of the spaceship operator:

<?php
    $a=250;
    $b=25;
    var_dump($a<=>$b);
?>

These comparison operators are commonly used in conditionals, such as if statements, to control the flow of program execution based on the evaluation of the expressions.