要明确地将一个值转换成 boolean,用 (bool) 或者 (boolean) 来强制转换。但是很多情况下不需要用强制转换,因为当运算符,函数或者流程控制结构需要一个 boolean 参数时,该值会被自动转换。
1.布尔值转换为字符串时,true转换为"1",false转换为""空字符串:
echo 'true as string gives [' . (string) true . "] not [true].\n";
echo 'false as string gives [' . (string) false . "] not [false].\n";
Output:
true as string gives [1] not [true].
false as string gives [] not [false].
如果想转换为"true"和"false"可用如下代码:
true ? 'true' : 'false'
2.当布尔值与非布尔值进行比较时,会将非布尔值转换为布尔值,再进行比较:
// someKey is a boolean true
$array = array('someKey'=>true);
// 将'false'转换为布尔值true,因此将什么都不会输出。
if($array['someKey'] != 'false')
echo 'The value of someKey is '.$array['someKey'];
//将会输出
if($array['someKey'] == 'false')
echo 'The value of someKey is '.$array['someKey'];
And the above will output
The value of someKey is 1
In short true == 'false' is true.