Current Location: Home> Latest Articles> PHP is_bool() Function Explained: How to Check if a Variable is a Boolean

PHP is_bool() Function Explained: How to Check if a Variable is a Boolean

M66 2025-06-19

PHP is_bool() Function Explained: How to Check if a Variable is a Boolean

In PHP development, checking whether a variable is a boolean value is a common task. PHP provides a built-in function called is_bool() that makes this process simple. This article will introduce how to use the is_bool() function to check the type of a variable, and help you understand its usage through practical code examples.

What is the is_bool() Function?

is_bool() is a function used to check if a variable is a boolean. If the variable is a boolean, the function returns true; otherwise, it returns false. This function is handy for quickly verifying whether a variable is true or false.

Example of Using the is_bool() Function

Let's take a look at a simple example to see how we can use the is_bool() function to check boolean values:

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

if (is_bool($var1)) {
    echo "Variable \$var1 is a boolean<br>";
} else {
    echo "Variable \$var1 is not a boolean<br>";
}

if (is_bool($var2)) {
    echo "Variable \$var2 is a boolean<br>";
} else {
    echo "Variable \$var2 is not a boolean<br>";
}

if (is_bool($var3)) {
    echo "Variable \$var3 is a boolean<br>";
} else {
    echo "Variable \$var3 is not a boolean<br>";
}

if (is_bool($var4)) {
    echo "Variable \$var4 is a boolean<br>";
} else {
    echo "Variable \$var4 is not a boolean<br>";
}
?>
  

The code above defines four variables and assigns them different values. It then uses the is_bool() function to check whether each variable is a boolean, and outputs the corresponding message based on the check results.

Output of the Example

When you execute the code above, you will get the following output:

Variable $var1 is a boolean
Variable $var2 is a boolean
Variable $var3 is not a boolean
Variable $var4 is not a boolean
  

As you can see, $var1 and $var2 are detected as booleans, while $var3 and $var4 are not. This is because $var1 and $var2 are assigned the boolean values true and false, whereas $var3 is assigned an integer value of 1, and $var4 is assigned the string value "true", which are not considered booleans.

Conclusion

The is_bool() function is a very useful tool in PHP programming to check if a variable is a boolean. By mastering and using this function, we can make our code more efficient and precise.

We hope this article helps you better understand and use the is_bool() function. By incorporating this function into your programming routine, your development process will become smoother and more effective.