PHP将所有数组都视为关联数组,因此没有任何内置函数。谁能推荐一种相当有效的方法来检查数组是否“是一个列表”(只包含从0开始的数字键)?
基本上,我希望能够区分这些:
$sequentialArray = [
'apple', 'orange', 'tomato', 'carrot'
];
这:
$assocArray = [
'fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot'
];
一种廉价而肮脏的方法是这样检查:
isset($myArray[count($myArray) - 1])
...如果你的数组是这样的,你可能会得到一个假阳性:
$myArray = array("1" => "apple", "b" => "banana");
一个更彻底的方法可能是检查钥匙:
function arrayIsAssociative($myArray) {
foreach (array_keys($myArray) as $ind => $key) {
if (!is_numeric($key) || (isset($myArray[$ind + 1]) && $myArray[$ind + 1] != $key + 1)) {
return true;
}
}
return false;
}
// this will only return true if all the keys are numeric AND sequential, which
// is what you get when you define an array like this:
// array("a", "b", "c", "d", "e");
or
function arrayIsAssociative($myArray) {
$l = count($myArray);
for ($i = 0; $i < $l, ++$i) {
if (!isset($myArray[$i])) return true;
}
return false;
}
// this will return a false positive on an array like this:
$x = array(1 => "b", 0 => "a", 2 => "c", 4 => "e", 3 => "d");