tags:

views:

114

answers:

2
$foo = 0;

if($foo == 'on') $foo = 1;

echo $foo;

It should be expected the above code outputs "0". However it doesn't, somehow $foo == 'on' results in TRUE, although this obviously is wrong. Replacing the expression with $foo === 'on' gives the right answer, so any suspicions this might be some typing issue seem to be confirmed.

Nevertheless, how can PHP think $foo was 'on' if $foo and 'on' even aren't of the same type? Is this a bug or some weird feature?

+3  A: 

In php is the loose comparison (==) of a string and the int 0 evaluated as True. While the strict comparison (===) also compares for the same types, that means it is compared if booth variables are strings or ints. But this evaluated as false, because $foo is an int and 'on' is a string. Also see the comparison tables on php.net: http://php.net/types.comparisons

seb
+3  A: 

this is a documented behaviour:

If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement.

SilentGhost