所以我有一个多暗阵列。我用boolean作为值定义了一些数组键:
$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
?)
答案 0 :(得分:3)
您正在将您的变量(包含(bool) true
/ (bool) false
)与boolean
进行比较。未定义Simple文本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
。
答案 1 :(得分:0)
您可以通过print_r验证问题是否与打印有关,而不是设置。以下行将输出bool(false)
var_dump( $geo_entries['hostip']['geoTypes']['city']);
同样var_dump( $geo_entries['hostip']['geoTypes']['city'] == false);
将输出bool(true)
和var_dump( $geo_entries['hostip']['geoTypes']['city'] == 0);
将输出bool(true)
稍微偏离主题: 通常,避免将布尔值处理为整数以使代码更具可读性是一个好主意,尤其是对于使用多种语言的开发人员。
答案 2 :(得分: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
答案 3 :(得分:0)
这不是你在PHP中进行类型比较的方式。如果要检查变量$foo
是否为布尔值,可以执行以下操作:
if (is_bool($foo))
{
// ...
}
您的示例实际上是将boolean
解释为字符串并检查在解释为布尔值时是否应将其视为true
。这将生成E_NOTICE消息(根据您的错误报告级别,可能会显示也可能不会显示)。
答案 4 :(得分:0)
False不等于0,因为您检查的变量的类型是布尔值。
http://us.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
该文档说以下值是错误的:
这并不是说boolean FALSE ==整数0。