Search⌘ K
AI Features

Comparison Operators

Explore the use of comparison operators in PHP to evaluate and compare values effectively. Understand the difference between equal and identical operators, and how the spaceship operator works to simplify comparisons. This lesson helps you apply these operators correctly in your code.

Basic operators

Comparison operators, as the name suggests, allow you to compare two values. The following table illustrates the different comparison operators in PHP:

Operator Name Example
== Equal a==b
=== Identical a===b
!= Not Equal a!=b
!== Not Identical a!==b
< Less than a<b
> Greater than a>b
<= Less than equal to a<=b
>= Greater than equal to a>=b

Note: For basic equality testing, the equal operator == is used. For more comprehensive checks, use the identical operator ===.

For instance, the == operator will return true when an integer 4 is compared with a character '4' but the === will return false. Run the code snippet below to see how this works:

PHP
<?php
$a = 4;
$b = '4';
if ($a == $b)
{
echo 'a and b are equal'; // this will be printed
}
if ($a === $b)
{ //try removing one = and see what happens
echo 'a and b are identical'; // this won't be printed
}
?>

In the above code snippet, the == operator returns true because the character '4' is cast to an integer.

Spaceship Operator

The spaceship operator (<=>) is a special kind of comparison operator. It

  • returns -1 if first expression is lesser than the second expression.
  • returns 1 if the first expression is greater than the second expression.
  • returns 0 if the first expression is equal to the second expression.

Run the code snippet below to see how it works

PHP
<?php
// Integers
echo (1<=>1) . ","; //prints 0
echo (1<=>2) . ","; //prints -1
echo (2<=>1); //prints 1
echo "\n"; //skips to next line
// Floats
echo (1.5<=>1.5) . ","; //prints 0
echo (1.5<=>2.5) . ","; //prints -1
echo (2.5<=>1.5); //prints 1
echo "\n"; //skips to next line
// Strings
echo ("a"<=>"a") . ","; //prints 0
echo ("a"<=>"b") . ","; //prints -1
echo ("b"<=>"a"); //prints 1
?>

Remember: Objects are not comparable, and doing so will result in undefined behavior.

Quick Quiz on Comparison Operators

Technical Quiz
1.

What is the result of the following code?

<?php
$a = 5;
$b = 2;
$c = 4;
if ($a < $b + $c)
{
    echo $a<=>($c - $b);
}
else
{
    echo ($c - $b) <=>$a;
}
?>
A.

0

B.

1

C.

-1


1 / 1

Now, let’s move on to logical operators in the next lesson.