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.
===
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:
$property
set, $a->property == $b->property
is true (hence recursively checked).They include:
>
)<
)>=
)<=
)!=
)!==
)$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)
$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)
$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)
$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
}