所以我有一个多调暗数组。我正在定义一些带有布尔值的数组键:
$geo_entries['hostip']['geoTypes']['country']=true;
$geo_entries['hostip']['geoTypes']['country_short']=true;
$geo_entries['hostip']['geoTypes']['city']=false;
$geo_entries['hostip']['geoTypes']['city_short']=false;
现在我对此进行了print_r()
,结果如下:
( [country] => 1 [country_short] => 1 [city] => [city_short] => )
现在如果我错了,请纠正我,但不false==0
吗?
我尝试快速检查值(对于布尔值):
if($geo_entries['hostip']['geoTypes']['city']==boolean){
//this returns false...
}
上述条件返回false
['hostip']['geoTypes']['city']
,但true
返回['hostip']['geoTypes']['country']
。两者之间的唯一区别是city
的值为 false
,而country
的值为 true
。
当我将值定义为0
而不是false
时 - 一切正常......
有一种感觉,我尴尬地错过了一些东西,这导致了这种误解。
有人愿意解释吗? - (为什么false!=0
?
您正在比较您的变量(包含(bool) true
/(bool) false
)与boolean
。简单文字boolean
未定义,PHP 将其作为字符串处理。
if($geo_entries['hostip']['geoTypes']['city']==boolean)
因此成为
if($geo_entries['hostip']['geoTypes']['city']=="boolean")
==
运算符将这些运算符与类型杂耍之后进行比较。 "boolean"
是一个非空字符串,被视为 (bool) true
。因此,您的比较归结为(bool) true == (bool) true
返回true
(bool) false == (bool) true
返回false
当然。
您可以验证问题是否与通过print_r打印而不是设置有关。 以下行将输出布尔值(假)
var_dump( $geo_entries['hostip']['geoTypes']['city']);
同样var_dump( $geo_entries['hostip']['geoTypes']['city'] == false);
将输出布尔值(真)
并且var_dump( $geo_entries['hostip']['geoTypes']['city'] == 0);
将输出布尔值(真)
稍微跑题了:通常,最好避免将布尔值处理为整数以使代码更具可读性,尤其是对于使用多种语言的开发人员。
foreach($geo_entries['hostip']['geoTypes'] as $key => $value) {
echo $key . ' is ' . (is_bool($value) ? 'boolean' : 'not boolean') . '<br />';
}
输出:
country is boolean
country_short is boolean
city is boolean
city_short is boolean
这不是你在 PHP 中进行类型比较的方式。如果要检查变量$foo
是否为布尔值,可以执行以下操作:
if (is_bool($foo))
{
// ...
}
您的示例实际上正在做的是将boolean
解释为字符串,并检查在解释为布尔值时是否应将其视为true
。这将生成一条E_NOTICE消息(根据您的错误报告级别,该消息可能可见,也可能不可见)。
False 不等于 0,因为您正在检查的变量的类型是布尔值。
http://us.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
文档说以下值为假:
- 布尔值 FALSE 本身
- 整数 0(零)
- 。
这并不是说布尔值 FALSE == 整数 0。