"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?
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
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".
'0' == 0 == false; or
(bool)'0' === (bool)(int)'0'
According to the PHP documentation on booleans, it says that:
When converting to boolean, the following values are considered
the empty string, and the string "0"
Every other value is considered TRUE (including any resource).
If you run:
It will print:
So it's working as expected.
To explicitly answer your question:
However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
This means that PHP's "autocast" will cast "0" to integer 0, which is
FALSE as well in a control structure like say an
protected by gnat Jun 9 at 6:19
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?