Comparison Operators
suggest changeEquality
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:
- of the same class
- have the same properties set, including dynamic properties
- for each property
$propertyset,$a->property == $b->propertyis true (hence recursively checked).
Other commonly used operators
They include:
- Greater Than (
\>) - Lesser Than (
\<) - Greater Than Or Equal To (
>=) - Lesser Than Or Equal To (
<=) - Not Equal To (
!=) - Not Identically Equal To (
!==) - Greater Than:
$a > $b, returnstrueif$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)
- Lesser Than:
$a < $b, returnstrueif$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)
- Greater Than Or Equal To:
$a >= $b, returnstrueif$a’s value is either greater than of$bor equal to$b, otherwise returnsfalse.
Example:
var_dump(2 >= 2); // prints bool(true)
var_dump(6 >= 1); // prints bool(true)
var_dump(1 >= 7); // prints bool(false)
- Smaller Than Or Equal To:
$a <= $b, returnstrueif$a’s value is either smaller than of$bor equal to$b, otherwise returnsfalse.
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
}