How to Use PHP’s is_bool() to Check Boolean Types

This guide explains the PHP is_bool() function, its syntax, parameters, return values, and provides concrete code examples that demonstrate how to determine whether a variable is of boolean type and handle different variable values correctly.

php Courses
php Courses
php Courses
How to Use PHP’s is_bool() to Check Boolean Types

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.

Concrete Code Example

<?php
$var1 = true;
$var2 = false;
$var3 = "true";
$var4 = 1;

// Check if variable is boolean
if (is_bool($var1)) {
    echo "变量var1是布尔类型";
} else {
    echo "变量var1不是布尔类型";
}

if (is_bool($var2)) {
    echo "变量var2是布尔类型";
} else {
    echo "变量var2不是布尔类型";
}

if (is_bool($var3)) {
    echo "变量var3是布尔类型";
} else {
    echo "变量var3不是布尔类型";
}

if (is_bool($var4)) {
    echo "变量var4是布尔类型";
} else {
    echo "变量var4不是布尔类型";
}
?>

Execution Result

变量var1是布尔类型
变量var2是布尔类型
变量var3不是布尔类型
变量var4不是布尔类型

Explanation

The example defines four variables: $var1 and $var2 are assigned the boolean values true and false, so is_bool() returns true for both, producing messages that they are boolean types. $var3 holds the string "true" and $var4 holds the integer 1; neither is a boolean, so is_bool() returns false and the script outputs that they are not boolean types.

Using is_bool() allows developers to reliably check variable types, which is useful for validating user input and ensuring data integrity and security in PHP 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.

BackendPHPbooleantype checkingis_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.