PHP Tutorial PHP Advanced PHP Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

PHP - comparison operators example



The example below illustrates the usage of PHP comparison operators: ==, !=, <>, ===, !==, >, <, >=, <=, <=>.

<?php
echo "10 == 10: ".(int)(10 == 10)."\n";
echo "10 != 10: ".(int)(10 != 10)."\n";
echo "10 === 10.0: ".(int)(10 === 10.0)."\n";
echo "10 !== 10.0: ".(int)(10 !== 10.0)."\n";
echo "10 <> 10: ".(int)(10 <> 10)."\n";
echo "10 < 20: ".(int)(10 < 20)."\n";
echo "10 > 20: ".(int)(10 > 20)."\n";
echo "10 <= 20: ".(int)(10 <= 20)."\n";
echo "10 >= 20: ".(int)(10 >= 20)."\n";

echo "\nSpaceship operator:\n";
echo "10 <=> 20: ".(int)(10 <=> 20)."\n";
echo "20 <=> 20: ".(int)(20 <=> 20)."\n";
echo "30 <=> 20: ".(int)(30 <=> 20)."\n";
?>

The output of the above code will be:

10 == 10: 1
10 != 10: 0
10 === 10.0: 0
10 !== 10.0: 1
10 <> 10: 0
10 < 20: 1
10 > 20: 0
10 <= 20: 1
10 >= 20: 0

Spaceship operator:
10 <=> 20: -1
20 <=> 20: 0
30 <=> 20: 1

These comparison operators generally return boolean results, which is very useful and can be used to construct conditional statement as shown in the example below:

<?php
function range_func($x){
  //&& (and) operator is used to combine conditions
  //returns true only when x >= 10 and x <= 25
  if($x >= 10 and $x <= 25)
    echo "$x belongs to range [10, 25].\n"; 
  else
    echo "$x do not belongs to range [10, 25].\n";
}

range_func(15);
range_func(25);
range_func(50);
?>

The output of the above code will be:

15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25].

❮ PHP - Operators

5