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:
\\>
)\\<
)>=
)<=
)!=
)!==
)