PHP Comparison Operators


Example

Equality

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

The identical operator works the same as the equal operator, requiring its operands have the same value, but also requires them to have the same data type.

For example, the sample below will display 'a and b are equal', but not 'a and b are identical'.

$a = 4;
$b = '4';
if ($a == $b) {
    echo 'a and b are equal'; // this will be printed
}
if ($a === $b) {
    echo 'a and b are identical'; // this won't be printed
}

When using the equal operator, numeric strings are cast to integers.

Comparison of objects

=== compares two objects by checking if they are exactly the same instance. This means that new stdClass() === new stdClass() resolves to false, even if they are created in the same way (and have the exactly same values).

== compares two objects by recursively checking if they are equal (deep equals). That means, for $a == $b, if $a and $b are:

  1. of the same class
  2. have the same properties set, including dynamic properties
  3. for each property $property set, $a->property == $b->property is true (hence recursively checked).

Other commonly used operators

They include:

  1. Greater Than (>)
  2. Lesser Than (<)
  3. Greater Than Or Equal To (>=)
  4. Lesser Than Or Equal To (<=)
  5. Not Equal To (!=)
  6. Not Identically Equal To (!==)
  1. Greater Than: $a > $b, returns true if $a's value is greater than of $b, otherwise returns false.

Example:

var_dump(5 > 2); // prints bool(true)
var_dump(2 > 7); // prints bool(false)
  1. Lesser Than: $a < $b, returns true if $a's value is smaller that of $b, otherwise returns false.

Example:

var_dump(5 < 2); // prints bool(false)
var_dump(1 < 10); // prints bool(true)
  1. Greater Than Or Equal To: $a >= $b, returns true if $a's value is either greater than of $b or equal to $b, otherwise returns false.

Example:

var_dump(2 >= 2); // prints bool(true)
var_dump(6 >= 1); // prints bool(true)
var_dump(1 >= 7); // prints bool(false)
  1. Smaller Than Or Equal To: $a <= $b, returns true if $a's value is either smaller than of $b or equal to $b, otherwise returns false.

Example:

var_dump(5 <= 5); // prints bool(true)
var_dump(5 <= 8); // prints bool(true)
var_dump(9 <= 1); // prints bool(false)

5/6. Not Equal/Identical To: To rehash the earlier example on equality, the sample below will display 'a and b are not identical', but not 'a and b are not equal'.

$a = 4;
$b = '4';
if ($a != $b) {
    echo 'a and b are not equal'; // this won't be printed
}
if ($a !== $b) {
    echo 'a and b are not identical'; // this will be printed
}