且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查 PHP 数组是关联的还是顺序的?

更新时间:2023-02-22 13:27:38

您提出了两个不太对等的问题:

You have asked two questions that are not quite equivalent:

  • 首先,如何判断一个数组是否只有数字键
  • 其次,如何判断一个数组是否有顺序数字键,从0开始
  • Firstly, how to determine whether an array has only numeric keys
  • Secondly, how to determine whether an array has sequential numeric keys, starting from 0

考虑您实际需要哪些行为.(可能两者都可以满足您的目的.)

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