Php – Why PHP treats “0” as FALSE in boolean contexts

booleanPHPstrings

"0", as a string containing one character, is not something empty intuitively. Why does PHP treat it as FALSE when converted to a boolean, unlike other programming languages?

Best Answer

PHP was designed (or, rather, evolved) for use with web requests, where you're frequently dealing with string input (URL parameters, or POST requests from a form in a browser). As such, it will automatically cast strings to other types.

A simple example of this is that '1' + '2' gives 3, not an error, or '12', or some other interpretation. By the same logic, the string '0' can be used as a numeric 0.

Meanwhile, like many languages, PHP treats certain values as "falsy" when cast to boolean - ones that are intuitively "empty", as you say. That includes numeric 0, as well as the empty string '' and the empty array []. In an if statement, the expression is explicitly cast to boolean, so if ( 0 ) is the same as if ( false ).

Putting these two things together, you get a conundrum: on the one hand, as you say '0' is a non-empty string; on the other hand, we have said that it can be used as a numeric 0, which is "empty". PHP opts to treat the "zero-ness" as more important than the "stringiness", so that '0' is considered "falsy".

In short: '0' == 0 == false; or (bool)'0' === (bool)(int)'0'