Using PHP is_bool() to Check Boolean Variables

This article explains PHP's built‑in is_bool() function, demonstrates its usage with several variable examples, shows the resulting output, and highlights why only true and false values are recognized as booleans in typical PHP programming contexts.

php Courses
php Courses
php Courses
Using PHP is_bool() to Check Boolean Variables

In PHP programming, checking whether a variable is a boolean is often required; the language provides the built‑in is_bool() function for this purpose.

The is_bool() function returns true if the supplied variable is of boolean type and false otherwise.

<?php
$var1 = true;
$var2 = false;
$var3 = 1;
$var4 = "true";

if (is_bool($var1)) {
    echo "变量 $var1 是布尔值<br>";
} else {
    echo "变量 $var1 不是布尔值<br>";
}
if (is_bool($var2)) {
    echo "变量 $var2 是布尔值<br>";
} else {
    echo "变量 $var2 不是布尔值<br>";
}
if (is_bool($var3)) {
    echo "变量 $var3 是布尔值<br>";
} else {
    echo "变量 $var3 不是布尔值<br>";
}
if (is_bool($var4)) {
    echo "变量 $var4 是布尔值<br>";
} else {
    echo "变量 $var4 不是布尔值<br>";
}
?>

The script defines four variables with different types—two booleans, an integer, and a string—and applies is_bool() to each, printing a message indicating whether the variable is a boolean.

变量 $var1 是布尔值
变量 $var2 是布尔值
变量 $var3 不是布尔值
变量 $var4 不是布尔值

From the output we see that only $var1 and $var2 are recognized as booleans because they were assigned the literal values true and false, while $var3 and $var4 are not.

Thus, is_bool() is a useful function for quickly determining a variable's boolean status, helping developers write more accurate and efficient PHP code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPbooleantype checkingis_bool
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.