Page 1 of 1

var_dump((bool) '0');

Posted: Tue Apr 03, 2007 2:41 pm
by Oren

Code: Select all

var_dump((bool) '0'); // false
var_dump((bool) '00'); // true
Any good reason why ((bool) '00') === true?

P.S I feel dumb, I was sure they were both false :oops:

Posted: Tue Apr 03, 2007 3:32 pm
by Chris Corbyn
I think 00 in string context will not be seen as an integer. It's like "0x00" would be the literal string. 00 is just PHP syntax for octal zero, but not in strings. A string evaluate to true.

Code: Select all

var_dump((bool)(int) "00");

Posted: Tue Apr 03, 2007 4:40 pm
by Oren

Code: Select all

var_dump((bool)(int) "00"); // === true
Anyway... I'm still confused :?

Posted: Tue Apr 03, 2007 5:03 pm
by feyd

Posted: Tue Apr 03, 2007 6:00 pm
by dreamscape
Oren wrote:

Code: Select all

var_dump((bool)(int) "00"); // === true
Anyway... I'm still confused :?
Actually that casts to boolean false. The string "00" casts to an integer as 0... The integer 0 casts to boolean as false.

In the case of var_dump((bool) '00');, the string "00" casts to boolean as true.

As it says in the link feyd gave, the only strings that cast to boolean false are an empty string and "0".

Posted: Wed Apr 04, 2007 2:39 am
by Oren
Yes I did, more than once. It still seems a bit odd to me, but whatever...

Posted: Wed Apr 04, 2007 4:35 am
by stereofrog
This is perhaps the weirdest rule in php: everything that looks like a number is treated like a number

Code: Select all

var_dump('123' == 123); // true
var_dump('0xCafe' == 51966); // true
var_dump('0123' == 0123); // false???
This was discussed many times on the internals list and although everyone agrees this is utterly stupid, it's too late to change. The best workaround is to use explicit typecasts and strict comparisons wherever possible.