Using PHP is_bool() to Check Boolean Variables
This article explains PHP's built-in is_bool() function, demonstrates how it determines whether a variable is a boolean, and provides practical code examples showing its behavior with true, false, integer, and string values.
In PHP programming, the built‑in is_bool() function is used to determine whether a variable holds a boolean value.
The function returns true if the argument is of type boolean and false otherwise, making it a simple boolean‑type checker.
Below is a complete example that defines four variables with different types and applies is_bool() to each:
";
} else {
echo "变量 $var1 不是布尔值
";
}
if (is_bool($var2)) {
echo "变量 $var2 是布尔值
";
} else {
echo "变量 $var2 不是布尔值
";
}
if (is_bool($var3)) {
echo "变量 $var3 是布尔值
";
} else {
echo "变量 $var3 不是布尔值
";
}
if (is_bool($var4)) {
echo "变量 $var4 是布尔值
";
} else {
echo "变量 $var4 不是布尔值
";
}
?>The script outputs which variables are booleans and which are not, producing:
变量 $var1 是布尔值
变量 $var2 是布尔值
变量 $var3 不是布尔值
变量 $var4 不是布尔值From the result we see that $var1 and $var2 are true booleans, while $var3 (an integer) and $var4 (a string) are not, illustrating how is_bool() distinguishes actual boolean types from other values.
In summary, is_bool() is a useful function for quickly checking variable types, and mastering its use can make PHP code more reliable and easier to debug.
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.