Using PHP’s is_bool() Function to Check Boolean Variables
This article explains how PHP’s built‑in is_bool() function determines whether a variable is a boolean, demonstrates its usage with four sample variables of different types, shows the resulting output, and highlights why only true and false values are recognized as booleans.
In PHP programming, checking whether a variable holds a boolean value is a common task, and the language provides the built‑in is_bool() function for this purpose.
The is_bool() function returns true if the supplied variable is of type boolean and false otherwise.
Below is a complete example that defines four variables with different types and uses is_bool() to test each one:
<code style="font-family: 'Operator Mono', Consolas, Monaco, Menlo, monospace; font-size: 12px; display: -webkit-box; padding: 15px 16px 16px; color: rgb(171, 178, 191)"><?php<br/>$var1 = true;<br/>$var2 = false;<br/>$var3 = 1;<br/>$var4 = "true";<br/><br/>if (is_bool($var1)) {<br/> echo "变量 $var1 是布尔值<br>";<br/>} else {<br/> echo "变量 $var1 不是布尔值<br>";<br/>}<br/><br/>if (is_bool($var2)) {<br/> echo "变量 $var2 是布尔值<br>";<br/>} else {<br/> echo "变量 $var2 不是布尔值<br>";<br/>}<br/><br/>if (is_bool($var3)) {<br/> echo "变量 $var3 是布尔值<br>";<br/>} else {<br/> echo "变量 $var3 不是布尔值<br>";<br/>}<br/><br/>if (is_bool($var4)) {<br/> echo "变量 $var4 是布尔值<br>";<br/>} else {<br/> echo "变量 $var4 不是布尔值<br>";<br/>}<br/>?></code>Running this script produces the following output, indicating which variables are recognized as booleans:
<code style="font-family: 'Operator Mono', Consolas, Monaco, Menlo, monospace; font-size: 12px; display: -webkit-box; padding: 15px 16px 16px; color: rgb(171, 178, 191)">变量 $var1 是布尔值<br/>变量 $var2 是布尔值<br/>变量 $var3 不是布尔值<br/>变量 $var4 不是布尔值<br/></code>The result shows that $var1 and $var2 are boolean values because they were assigned the literals true and false. In contrast, $var3 holds an integer (1) and $var4 holds a string ("true"), so is_bool() correctly reports them as non‑boolean.
In summary, the is_bool() function is a simple yet powerful tool for quickly determining a variable’s boolean status, which is essential for reliable type checking in PHP applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
