Using PHP’s is_bool() Function to Check Boolean Variables
This article explains how PHP’s built‑in is_bool() function determines whether a variable is a boolean, demonstrates its usage with four sample variables of different types, shows the resulting output, and highlights why only true and false values are recognized as booleans.
In PHP programming, checking whether a variable holds a boolean value is a common task, and the language provides the built‑in is_bool() function for this purpose.
The is_bool() function returns true if the supplied variable is of type boolean and false otherwise.
Below is a complete example that defines four variables with different types and uses is_bool() to test 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>";
}
?>Running this script produces the following output, indicating which variables are recognized as booleans:
变量 $var1 是布尔值
变量 $var2 是布尔值
变量 $var3 不是布尔值
变量 $var4 不是布尔值The result shows that $var1 and $var2 are boolean values because they were assigned the literals true and false . In contrast, $var3 holds an integer (1) and $var4 holds a string ("true"), so is_bool() correctly reports them as non‑boolean.
In summary, the is_bool() function is a simple yet powerful tool for quickly determining a variable’s boolean status, which is essential for reliable type checking in PHP applications.
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.