(PHP 5 >= 5.5.0)
boolval — Get the boolean value of a variable
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([1, 2]) ? '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
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;
}
}
?>