Printing Boolean Values in PHP
The provided PHP code exemplifies an issue where a Boolean value of false does not display when echoed. While the code for true outputs 1, there may be cases where one desires to explicitly display false instead of an empty string.
One solution involves utilizing a conditional statement:
$bool_val = (bool)false; if (!$bool_val) { echo 'false'; }
However, this approach requires an additional if statement, which may not be ideal.
A more concise solution employs the ternary operator:
echo $bool_val ? 'true' : 'false';
This code checks the truthiness of $bool_val and outputs 'true' if true or 'false' if false.
Alternatively, for scenarios where you only wish to display the 'false' string when the value is indeed false, you can use:
echo !$bool_val ? 'false' : '';
This code employs the logical NOT operator to invert the Boolean value, and then outputs 'false' only when the inverted value is true (i.e., when $bool_val is false).
The above is the detailed content of How Can I Print Boolean Values (true/false) in PHP Instead of 1 or an Empty String?. For more information, please follow other related articles on the PHP Chinese website!