tags:

views:

73

answers:

2

In PHP, can someone explain to me why this resolves to true:

'NONE' == 0
+3  A: 

Because the string is 0 when evaluated in a number context. Quoting:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

So it depends on what the string contains.

Also, see the chapter on Type Juggling and Type Comparison in the PHP Manual.

Gordon
As described here: http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion
Mchl
@Mchl yes, thanks. Added it.
Gordon
so ... NONE is a keyword? Like 'false'? (I'm asking this while reading the chapter)
Putr
@Putr no, its a string. nothing more.
Gordon
@Putr Not really. Any string in a boolean context evaluates to true. So `('false' == false)` is false, `('false' == true)` is true.
NullUserException
@NullUser it's not a boolean context here though, but a numeric one, so `('10' == 10)` and `('0xFF' == 255)` and `('16 foo' == 16)` is all true.
Gordon
+12  A: 

Because any non-numerical string cast to int will turn into 0.

If you don't want that to happen, use ===, the identical operator.

Read:
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/types.comparisons.php

NullUserException
Thank you, now i understand.
Putr
This is just nitpicking, but `is_numeric('16 foo')` is `FALSE`, e.g. a non-numerical string and typecasting it to int will turn it into 16, not 0.
Gordon
@Gordon PHP works in mysterious ways, doesn't it?
NullUserException
@NullUser not in this case :) it's all described at http://de.php.net/manual/en/language.types.string.php#language.types.string.conversion
Gordon