var_dump((bool) '0');

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

var_dump((bool) '0');

Post 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:
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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");
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

Code: Select all

var_dump((bool)(int) "00"); // === true
Anyway... I'm still confused :?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
dreamscape
Forum Commoner
Posts: 87
Joined: Wed Jun 08, 2005 10:06 am
Contact:

Post 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".
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

Yes I did, more than once. It still seems a bit odd to me, but whatever...
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post 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.
Post Reply