问题
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