Using PHP is_bool() to Check Whether a Variable Is Boolean
This article explains how to use PHP's built-in is_bool() function to determine whether a variable holds a boolean value, provides clear code examples with four different variables, shows the expected output, and discusses why certain values are not considered booleans.
In PHP programming we often need to verify if a variable is a boolean. PHP provides the built-in function is_bool() for this purpose.
The is_bool() function returns true when the supplied variable is of boolean type and false otherwise.
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 applies is_bool() to each variable and prints a message indicating whether the variable is a boolean.
Running the code produces the following output:
变量 $var1 是布尔值
变量 $var2 是布尔值
变量 $var3 不是布尔值
变量 $var4 不是布尔值From the results we see that $var1 and $var2 are recognized as booleans because they were assigned the literal values true and false . $var3 (integer 1) and $var4 (string "true") are not booleans, so is_bool() returns false for them.
In summary, the is_bool() function is a handy tool for quickly determining a variable's boolean status, which is a common requirement in robust 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.