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.

php Courses
php Courses
php Courses
Using PHP is_bool() to Check Boolean Variables

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:

<?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 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Tutorialbooleanfunctionis_booltype-checking
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.