Home >Backend Development >PHP Tutorial >How Can I Accurately Echo Boolean Values (true/false) in PHP?
PHP Echo Boolean Values Accurately
In PHP, casting a boolean value to a string typically results in "1" or an empty string depending on its truthiness. However, some cases may require explicitly printing "false" when the boolean value is indeed false.
Consider the following code:
$bool_val = (bool)false; echo $bool_val;
This code will not output anything, as casting false to a string results in an empty string. Similarly, for true, casting to a string results in "1".
Alternative Solutions
To explicitly echo "false" or "0" when the boolean value is false, the following options can be used:
echo $bool_val ? 'true' : 'false';
This ternary operator evaluates the value of $bool_val and returns "true" if it's true, or "false" if it's false.
echo $bool_val ?? 'false';
The Coalesce Operator, introduced in PHP 7.0, returns the first non-null value of its arguments. In this case, if $bool_val is false (which evaluates to null), the "false" string will be returned.
echo !$bool_val ? 'false' : '';
This technique uses the logical "not" operator to reverse the boolean value. If $bool_val is false, it will be reversed to true, causing the conditional operator to evaluate to "false".
The above is the detailed content of How Can I Accurately Echo Boolean Values (true/false) in PHP?. For more information, please follow other related articles on the PHP Chinese website!