Variable handling 函数
在线手册:中文  英文

boolval

(PHP 5 >= 5.5.0)

boolvalGet the boolean value of a variable

说明

boolean boolval ( mixed $var )

Returns the boolean value of var.

参数

var

The scalar value being converted to a boolean.

返回值

The boolean value of var.

范例

Example #1 boolval() examples

<?php
echo '0:        '.(boolval(0) ? 'true' 'false')."\n";
echo 
'42:       '.(boolval(42) ? 'true' 'false')."\n";
echo 
'0.0:      '.(boolval(0.0) ? 'true' 'false')."\n";
echo 
'4.2:      '.(boolval(4.2) ? 'true' 'false')."\n";
echo 
'"":       '.(boolval("") ? 'true' 'false')."\n";
echo 
'"string": '.(boolval("string") ? 'true' 'false')."\n";
echo 
'[1, 2]:   '.(boolval([12]) ? 'true' 'false')."\n";
echo 
'[]:       '.(boolval([]) ? 'true' 'false')."\n";
echo 
'stdClass: '.(boolval(new stdClass) ? 'true' 'false')."\n";
?>

以上例程会输出:

0:        false
42:       true
0.0:      false
4.2:      true
"":       false
"string": true
[1, 2]:   true
[]:       false
stdClass: true

参见


Variable handling 函数
在线手册:中文  英文

用户评论:

luigi_cangiano at hotmail dot it (2013-07-01 08:28:28)

// Hack for old php versions to use boolval()
if(!function_exists('boolval')) {
function boolval($var = null) {
$back = false;
switch(gettype($var)) {
case 'boolean':
$back = $var;
break;
case 'float':
case 'double':
$var = intval($var);
case 'integer':
$back = $var !== 0;
break;
case 'string':
switch(strtolower($var)) {
case 'y':
case 's':
case 'true':
case 'vero':
case '1':
$back = true;
break;
case 'n':
case 'false':
case 'falso':
case '0':
$back = false;
break;
default:
$back = (bool)$var;
}
break;
default:
$back = (bool)$var;
break;
}
return $back;
}
}

Linuxatico (2013-05-14 08:41:58)

Well, considering that is common to code in OO, this snippet is not right, this solved for me:
class A {
public function boolVal($val)
{
if (!function_exists('boolval')) {
return (bool) $val;
}
else { return boolval($val); }
}
}
and in my project I do:
$a = new A();
$a->boolVal($val);

info at lomalkin dot ru (2013-03-15 11:08:19)

<?

// Hack for old php versions to use boolval()

if (!function_exists('boolval')) {
        function boolval($val) {
                return (bool) $val;
        }
}
?>

易百教程