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<br/>$var1 = true;<br/>$var2 = false;<br/>$var3 = "true";<br/>$var4 = 1;<br/><br/>// Check if variables are boolean<br/>if (is_bool($var1)) {<br/>    echo "Variable var1 is boolean";<br/>} else {<br/>    echo "Variable var1 is not boolean";<br/>}<br/>if (is_bool($var2)) {<br/>    echo "Variable var2 is boolean";<br/>} else {<br/>    echo "Variable var2 is not boolean";<br/>}<br/>if (is_bool($var3)) {<br/>    echo "Variable var3 is boolean";<br/>} else {<br/>    echo "Variable var3 is not boolean";<br/>}<br/>if (is_bool($var4)) {<br/>    echo "Variable var4 is boolean";<br/>} else {<br/>    echo "Variable var4 is not boolean";<br/>}<br/>?>

The execution result is:

Variable var1 is boolean<br/>Variable var2 is boolean<br/>Variable var3 is not boolean<br/>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.

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.

BackendPHPbooleanphp-functionsis_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.