Using PHP's is_bool() Function to Check Boolean Variables

This article explains how the PHP is_bool() function determines whether a variable holds a boolean value, provides a complete code example with four different variables, shows the resulting output, and discusses why only true and false are recognized as booleans.

php Courses
php Courses
php Courses
Using PHP's is_bool() Function to Check Boolean Variables

In PHP programming, checking whether a variable is a boolean is a common task, and the built‑in is_bool() function makes this straightforward. This article introduces the usage of is_bool() and provides practical code examples.

The is_bool() function returns true if the supplied variable is of boolean type, otherwise it returns false. Below is a sample script 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 the script 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. In contrast, $var3 (an integer 1) and $var4 (the string "true") are not booleans, so is_bool() returns false for them.

In summary, the is_bool() function is a useful tool for quickly determining a variable's boolean status, which is essential for many programming scenarios where type checking ensures correct logic flow.

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.

Backend DevelopmentPHPCode Exampleboolean checkis_bool
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.