简体   繁体   中英

Boolean values of PHP strings

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.

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM