更新时间:2023-02-22 13:27:38
您提出了两个不太对等的问题:
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.)
第一个问题(简单地检查所有键是否为数字)是船长 kurO 回答得很好.
The first question (simply checking that all keys are numeric) is answered well by Captain 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