You have asked two questions that are not quite equivalent:
(您问了两个不完全相同的问题:)
Consider which of these behaviours you actually need.
(考虑您实际上需要哪种行为。)
(It may be that either will do for your purposes.) ((这也许可以满足您的目的。))
The first question (simply checking that all keys are numeric) is answered well by Captain kurO .
(kurO上尉很好地回答了第一个问题(只需检查所有键是否都是数字)。)
For the second question (checking whether the array is zero-indexed and sequential), you can use the following function:
(对于第二个问题(检查数组是否为零索引和顺序索引),可以使用以下函数:)
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
var_dump(isAssoc(['a', 'b', 'c'])); // false
var_dump(isAssoc(["0" => 'a', "1" => 'b', "2" => 'c'])); // false
var_dump(isAssoc(["1" => 'a', "0" => 'b', "2" => 'c'])); // true
var_dump(isAssoc(["a" => 'a', "b" => 'b', "c" => 'c'])); // true
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…