Comparison Operators

suggest change

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
}

With ==, PHP converts the operands to a common type. A numeric string is compared as a number, so 4 == '4' is true. The conversion is not limited to integers: '4.5' == 4.5 is also true, and 'php' == 0 is true.

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 exactly the same property 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. Less Than (<)
  3. Greater Than Or Equal To (>=)
  4. Less Than Or Equal To (<=)
  5. Not Equal To (!=)
  6. Not Identically Equal To (!==)
  7. Greater Than: $a > $b returns true if $a is greater than $b, otherwise false.

Example:

var_dump(5 > 2); // prints bool(true)
var_dump(2 > 7); // prints bool(false)
  1. Less Than: $a < $b returns true if $a is smaller than $b, otherwise 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 is greater than or equal to $b, otherwise false.

Example:

var_dump(2 >= 2); // prints bool(true)
var_dump(6 >= 1); // prints bool(true)
var_dump(1 >= 7); // prints bool(false)
  1. Less Than Or Equal To: $a <= $b returns true if $a is less than or equal to $b, otherwise 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
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents