一个键可以是一个整数或者一个字符串。如果一个键是标准的
如果是整数的表示形式,则会将其解释为(即。
"8" will be interpreted as 8, while "08" will be interpreted as "08").
键中的浮点数被截断为整数
数组类型在 PHP 中是相同的类型,它们都可以包含整数
和字符串索引。
I ran into this problem on an array with both '0' and '' as keys. It meant that I couldn't check my array keys with either == or ===.
$array=array(''=>'empty', '0'=>'zero', '1'=>'one');
echo "Test 1\n";
foreach ($array as $key=>$value) {
if ($key == '') { // Error - wrongly finds '0' as well
echo "$value\n";
}
}
echo "Test 2\n";
foreach ($array as $key=>$value) {
if ($key === '0') { // Error - doesn't find '0'
echo "$value\n";
}
}
解决办法是在使用前将数组键强制转换回字符串。
echo "Test 3\n";
foreach ($array as $key=>$value) {
if ((string)$key == '') { // Cast back to string - fixes problem
echo "$value\n";
}
}
echo "Test 4\n";
foreach ($array as $key=>$value) {
if ((string)$key === '0') { // Cast back to string - fixes problem
echo "$value\n";
}
}