15

"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?

2 Answers2

17

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 - things 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'

IMSoP
  • 5,947
3

According to the PHP documentation on booleans, it says that:

When converting to boolean, the following values are considered FALSE
...
the empty string, and the string "0"
...

Otherwise:

Every other value is considered TRUE (including any resource).

If you run:

var_dump((bool) "0");

It will print:

bool(false)

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 if() statement.

kayess
  • 241