In PHP, false == true

Let’s go with a trivia.

What is the output of

var_dump((bool) "0");
var_dump((bool) "toto");
var_dump((bool) ("0" == "toto"));

You might think like I did

bool(false)
bool(true)
bool(false)

and you would be wrong. The output is:

bool(false)
bool(true)
bool(true)

Hold on, what? So if “0” == “toto” is true, then given that “0” is false and “toto” is true, then I get the crazy conclusion that false == true. Woa!

When reading php “empty” documentation, we can confirm that the string “0” is considered empty and hence converts to the boolean false. Then how is “0” == “toto” true? I have no idea.

Of course, if you use the triple equality operator, you get the expected result.

var_dump((bool) ("0" === "toto"));

will return false;

Conclusion: use the triple equality operator as much as you can.

PS.: If anyone knows why this is so, feel free to leave a reply.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.