Boolean values of PHP strings

81 views Asked by At

I am trying to understand the truthiness of strings in PHP. I thought it might be like other scripting language like Javascript or Python.

> var_dump((bool)"");
bool(false);

> var_dump((bool)"hello");
bool(true);

Okay, makes sense.

Then I tried

> var_dump((bool)"0");
bool(false);

Really? That's weird. I guess PHP tries to parse the string as a number first. So this should also be false

> var_dump((bool)"00");
bool(true);

Huh?!? I am really confused, and would like to know what makes a string truthy or not.

I haven't been able to find anything so far.

2

There are 2 answers

0
nickb On

See the docs for converting to boolean:

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags

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

0
Fabio On

From booleans php documentation

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags

So yes, your example have sense, 0 is a boolean false while 00 is a string and is true