Using PHP is_bool() to Check Boolean Variables
This article explains how the PHP is_bool() function can be used to determine whether a variable holds a boolean value, provides clear code examples with different variable types, and shows the resulting output to illustrate correct usage.
In PHP programming, it is often necessary to verify whether a variable is a boolean. PHP provides the built‑in is_bool() function for this purpose.
The is_bool() function returns true if the supplied variable is of boolean type, otherwise it returns false.
Below is a practical example that defines four variables with different types and uses is_bool() to check each one:
<?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 creates $var1 (boolean true), $var2 (boolean false), $var3 (integer 1), and $var4 (string "true"). It then checks each variable with is_bool() and prints whether the variable is a boolean.
Running the code produces the following output:
变量 $var1 是布尔值<br/>变量 $var2 是布尔值<br/>变量 $var3 不是布尔值<br/>变量 $var4 不是布尔值<br/>From the results, $var1 and $var2 are identified as booleans, while $var3 and $var4 are not, demonstrating that is_bool() correctly distinguishes true boolean values from other types such as integers and strings.
In summary, the is_bool() function is a useful tool for quickly checking variable types in PHP, helping developers write more reliable and type‑safe code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
