几天前,我使用的API返回了array
$data = [
"amount" => 0, //integer
"last_login" => "NA", //string
"active" => false //boolean
...
];
我想将所有“ NA”都强制转换为boolean
(以false
的形式使用)
foreach ($data as $key => $value) {
if($value == "NA"){ //if value is equal to "NA" set as false
$data[$key] = false;
}
}
预期输出为:
Array
(
[amount] => 0
[last_login] => false
[active] => false
)
但是我得到了:
Array
(
[amount] => false //here breaks if amount is passed as 0, because expected Integer for some calculations
[last_login] => false
[active] => false
)
经过几小时的破坏,我发现php
将0
视为NA
(“ NA” == 0):
var_dump("NA" == 0); //bool(true)
var_dump(0 == null); //bool(true)
var_dump("NA" == null); //bool(false)
//more
var_dump(empty("NA")); //bool(false)
var_dump(empty(null)); //bool(true)
var_dump(empty(0)); //bool(true)
这里是一个问题,为什么NA
等于0
,我试图在php.net
上找到DataTypes的引用表,但是没有提及NA
及其相关内容与0
相等。