There are two types of comparison: loose comparison with ==
and strict comparison with ===
. Strict comparison ensures both the type and value of both sides of the operator are the same.
// Loose comparisons
var_dump(1 == 1); // true
var_dump(1 == "1"); // true
var_dump(1 == true); // true
var_dump(0 == false); // true
// Strict comparisons
var_dump(1 === 1); // true
var_dump(1 === "1"); // false
var_dump(1 === true); // false
var_dump(0 === false); // false
// Notable exception: NAN — it never is equal to anything
var_dump(NAN == NAN); // false
var_dump(NAN === NAN); // false
You can also use strong comparison to check if type and value don't match using !==
.
A typical example where the ==
operator is not enough, are functions that can return different types, like strpos
, which returns false
if the searchword
is not found, and the match position (int
) otherwise:
if(strpos('text', 'searchword') == false)
// strpos returns false, so == comparison works as expected here, BUT:
if(strpos('text bla', 'text') == false)
// strpos returns 0 (found match at position 0) and 0==false is true.
// This is probably not what you expect!
if(strpos('text','text') === false)
// strpos returns 0, and 0===false is false, so this works as expected.