Touchpad
Touchpad

Reputation: 722

checking if 0 is equal to any string always returns true

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

Answers (3)

user5570620
user5570620

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.

From this post

Upvotes: 2

Daan
Daan

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

Liam Wiltshire
Liam Wiltshire

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

Related Questions