Backend Development 4 min read

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.

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

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