Home >Backend Development >PHP Tutorial >How Can I Print Boolean Values (true/false) in PHP Instead of 1 or an Empty String?

How Can I Print Boolean Values (true/false) in PHP Instead of 1 or an Empty String?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 14:37:09907browse

How Can I Print Boolean Values (true/false) in PHP Instead of 1 or an Empty String?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn