Why does 0 == 'empty'?

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
mrcoffee
Forum Commoner
Posts: 31
Joined: Tue Nov 10, 2009 3:03 pm
Location: Wyoming, USA

Why does 0 == 'empty'?

Post by mrcoffee »

After a few hours of frustration, I found that 0 == "empty" evaluates as true.

I can understand why 0 == "null" would be true and why 0 === null would be false, but I don't get what's happening above.

Can anyone explain this to me?

Thank you.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Why does 0 == 'empty'?

Post by Darhazer »

0 is equal to any string, that does not begin with a number.
This is because when you are comparing two different types, one of the operands is cast to the type of the another.
And when you cast a string to integer, it becomes 0 (or if it begins with numbers, it becomes the numeric part of the string)
You can read more at http://php.net/manual/en/language.opera ... arison.php
mrcoffee
Forum Commoner
Posts: 31
Joined: Tue Nov 10, 2009 3:03 pm
Location: Wyoming, USA

Re: Why does 0 == 'empty'?

Post by mrcoffee »

Okay, got it now. Apparently I did not understand why 0 == 'null' :)

Thank you, that was really bothering me.
Post Reply