PHP - Using Comparison operators

Introduction

Comparison operators take two operands and compare them, returning the result of the comparison usually as a Boolean, that is, true or false.

There are four comparisons that are very intuitive:

Comparison operators Meaning
< less than
<= less or equal to
>greater than
>=greater than or equal to

There is the special operator <=> (called spaceship).

It compares both the operands and returns an integer instead of a Boolean.

When comparing a with b, the result will be

  • less than 0 if a is less than b,
  • 0 if a equals b, and
  • greater than 0 if a is greater than b.

Demo

<?php
    var_dump(2 < 3); // true 
    var_dump(3 < 3); // false 
    var_dump(3 <= 3); // true 
    var_dump(4 <= 3); // false 
    var_dump(2 > 3); // false 
    var_dump(3 >= 3); // true 
    var_dump(3 > 3); // false 
    var_dump(1 <=> 2); // int less than 0 
    var_dump(1 <=> 1); // 0 
    var_dump(3 <=> 2); // int greater than 0 
?>/*w ww .  j  a  va  2s  . c o m*/

Result

There are comparison operators to evaluate if two expressions are equal or not, but you need to be careful with type juggling.

The == (equals) operator evaluates two expressions after type juggling.

It will try to transform both expressions to the same type, and then compare them.

Instead, the === (identical) operator evaluates two expressions without type juggling, so even if they look the same, if they are not of the same type, the comparison will return false.

The same applies to != or <> (not equal to) and !== (not identical):

Demo

<?php
    $a = 3; /*from  w w  w.ja  v a2 s  . c  o  m*/
    $b = '3'; 
    $c = 5; 
    var_dump($a == $b); // true 
    var_dump($a === $b); // false 
    var_dump($a != $b); // false 
    var_dump($a !== $b); // true 
    var_dump($a == $c); // false 
    var_dump($a <> $c); // true 
?>

Result

When asking if a string and an integer that represent the same number are equal, it replies affirmatively;

PHP first transforms both to the same type.

When asked if they are identical, it replies they are not as they are of different types.

Related Topic