Reputation: 722
I have come across this php "error" on many occations but I've never stopped to thing about it. So this is me asking for someone to help me understand this:
$int = 0;
var_dump($int == "string");
var_dump(false == "string");
var_dump(false == $int);
Upvotes: 0
Views: 68
Reputation:
The PHP Manual has a type Comparison Table in it, which gives you an idea of what happens when comparing variables of two different data types.
Your first example (a 'loose' comparison since it does not also check the data types of the two operands) implicitly converts the string on the left to an integer. Since it does not start with a number, the string is converted to the integer 0, which is equal to the integer 0.
Your second example compares not only the values but the types as well. Since the type is different, the comparison is false.
Upvotes: 2
Reputation: 12246
We use ==
for loose comparisons and ===
for strict comparisons.
$int = 0;
var_dump($int === "string"); //false
var_dump(false === "string"); //false
var_dump(false === $int); //false
Upvotes: 2
Reputation: 1264
In PHP, the == operator checks that two values are equivalent - in other words, PHP will use type juggling where required, but things like 0 == false, 1 == '1' etc will be true.
To check that two values are identical (including type), use the === operator.
Upvotes: 0