Backend Development 3 min read

Using PHP is_bool() to Determine Boolean Variables

This article explains PHP's is_bool() function, its syntax, parameters, return values, and provides a detailed code example demonstrating how to check whether variables are of boolean type, along with analysis of the output and practical usage tips.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP is_bool() to Determine Boolean Variables

In PHP, the is_bool() function is used to determine whether a variable is of boolean type. It returns true if the variable is boolean, otherwise false.

Syntax:

bool is_bool ( mixed $var )

Parameter Description:

$var : The variable to be tested.

Return Value:

If $var is a boolean, the function returns true; otherwise it returns false.

Specific Code Example:

<?php
$var1 = true;
$var2 = false;
$var3 = "true";
$var4 = 1;
// Check if variables are boolean
if (is_bool($var1)) {
echo "Variable var1 is boolean";
} else {
echo "Variable var1 is not boolean";
}
if (is_bool($var2)) {
echo "Variable var2 is boolean";
} else {
echo "Variable var2 is not boolean";
}
if (is_bool($var3)) {
echo "Variable var3 is boolean";
} else {
echo "Variable var3 is not boolean";
}
if (is_bool($var4)) {
echo "Variable var4 is boolean";
} else {
echo "Variable var4 is not boolean";
}
?>

The execution result is:

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

Analysis:

In the example, $var1 and $var2 are assigned true and false respectively, so is_bool() returns true for both. $var3 holds the string "true", which is not a boolean, so the function returns false. $var4 is an integer 1, also not a boolean, resulting in false.

Conclusion:

Using is_bool() allows developers to easily verify whether a variable is a boolean, which is useful for validating user input and ensuring data integrity in applications.

backendPHPBooleantype checkingphp-functionsis_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.