0

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);
Touchpad
  • 662
  • 2
  • 12
  • 29
  • 4
    http://us3.php.net/types.comparisons –  Feb 11 '16 at 13:33
  • Thanks found the answer in that url to clarify the answer in this case is: "This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0." – Touchpad Feb 11 '16 at 13:37
  • 1
    Possible duplicate of [Why does (0 == 'Hello') return true in PHP?](http://stackoverflow.com/questions/5894350/why-does-0-hello-return-true-in-php) – A.L Feb 11 '16 at 13:39

3 Answers3

2

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
Daan
  • 12,099
  • 6
  • 34
  • 51
  • I know how to fix it I was mearly asking why, I found the why in the link shared by @divyesh-savaliya – Touchpad Feb 11 '16 at 13:36
  • 0 is an int, so in this case it is going to cast 'string' to an int. Which is not parseable as one, and will become 0. A string '0string' would become 0, and would match! – Daan Feb 11 '16 at 13:38
  • Same goes for `false == 0`. When parsing 0 as a boolean it becomes `false`. Same goes for `true == anyothernumber` – Daan Feb 11 '16 at 13:40
2

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

Community
  • 1
  • 1
0

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.

Liam Wiltshire
  • 1,254
  • 13
  • 26