is_bool

(PHP 4, PHP 5, PHP 7, PHP 8)

is_bool 检测变量是否是布尔值

说明

is_bool ( mixed $value ) : bool

检查变量是否为布尔值。

参数

value

要检查的变量。

返回值

如果 value 是布尔值则返回 true,否则返回 false

范例

示例 #1 is_bool() 示例

<?php
$a 
false;
$b 0;

// 因为 $a 是布尔值,所以结果为 true
if (is_bool($a) === true) {
    echo 
"Yes, this is a boolean";
}

// 因为 $b 不是布尔值,所以结果为 false
if (is_bool($b) === false) {
    echo 
"No, this is not a boolean";
}
?>

参见

add a note add a note

User Contributed Notes 2 notes

up
7
phil
2 years ago
It should be stated that this function returns true if the _type_ of it's argument is boolean. It does not convert or coerce the value to a boolean type, not sure why so many comments focus on how to do this.
However, if you arrived here looking for a solution to convert a value to a boolean type, use this:

to_bool($x) { return (bool)$x; }
up
-1
Michael Smith
7 years ago
The function in the last comment also converts the string 'false' to a true boolean. Here's a function that does what I think was intended:

<?php
function toBool($var) {
  if (!
is_string($var)) return (bool) $var;
  switch (
strtolower($var)) {
    case
'1':
    case
'true':
    case
'on':
    case
'yes':
    case
'y':
      return
true;
    default:
      return
false;
  }
}
To Top