Is there a way to get “true”/“false” string values from a Boolean in PHP?

蹲街弑〆低调 提交于 2020-01-24 09:23:06

问题


When I cast to Boolean (using (bool)), is there a built in way to get PHP to actually return the constants true or false. At the moment I'm getting 1 or blank, which evaluate to true and false respectively.

I want the value returned for clearer semantics. However, if I can't get it, I'll just settle with 1 and blank.


回答1:


PHP displays boolean values as 1 (true) or empty string (false) when outputted.

If you want to check if it's true or false use == (if implicit conversion is OK) or === (if it's not). For example:

echo $val ? 'true' : 'false'; // implicit conversion
echo $val === true ? 'true' : 'false'; // no conversion

I don't know of any way to make PHP output boolean values natively as true or false.




回答2:


In case you're too lazy to do a comparison and echo a string or if you just want to keep it short you can use :

var_export($boolean, true); // the second parameter is to return and not output

PHP: var_export




回答3:


If you're looking for the strings "true" and "false," a ternary conditional would be perfect:

<?=(($boolean) ? "true" : "false")?>


来源:https://stackoverflow.com/questions/2249235/is-there-a-way-to-get-true-false-string-values-from-a-boolean-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!