php教程

is_bool

(PHP 4, PHP 5, PHP 7)

is_bool 检测变量是否是布尔型

描述

is_bool ( mixed $var ) : bool

如果 varboolean 则返回 TRUE

Example #1 is_bool() 示例

<?php
$a 
false;
$b 0;

// 因为 $a 是布尔型,所以结果为真
if (is_bool($a)) {
    print 
"Yes, this is a boolean";
}

// 因为 $b 不是布尔型,所以结果为非真
if (is_bool($b)) {
    print 
"Yes, this is a boolean";
}
?>

参见 is_array()is_float()is_int()is_integer()is_string()is_object()

User Contributed Notes

phil 10-Jan-2019 06:21
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; }
Michael Smith 17-Nov-2013 01:17
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;
  }
}

CopyRight © 2008-2022 verySource.Com All Rights reserved. 京ICP备17048824号-1 京公网安备:11010502034788