Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is integer 0 equal to a string in PHP? [duplicate]

Possible Duplicate:
How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?

Why this

var_dump(0 == "string");

outputs this

bool(true)

Isn't the context of == operator supposed to convert 0 into FALSE and "string" into TRUE according to this set of rules?

like image 603
Desmond Hume Avatar asked Dec 03 '22 00:12

Desmond Hume


2 Answers

var_dump(0 == "string");

is doing a numeric (integer) comparison

0 is an integer, so "string" is converted to an integer to do the comparison, and equates to an integer value of 0, so 0 == 0 is true

Se the comparison with various types table in the PHP documentation for details

like image 147
Mark Baker Avatar answered Dec 24 '22 09:12

Mark Baker


The table shown here is more fit for your case.

It shows TRUE for comparing 0 with "php".

Within the comparison you do not convert both operands to a boolean, but one operand will be converted to match the type of the other operand. In your case the string gets converted to an integer, which results in another 0. This gives you 0 == 0, which yields true.

like image 31
Sirko Avatar answered Dec 24 '22 08:12

Sirko