Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

php - 如何检查PHP数组是关联数组还是顺序数组?(How to check if PHP array is associative or sequential?)

PHP treats all arrays as associative, so there aren't any built in functions.

(PHP将所有数组视为关联数组,因此没有任何内置函数。)

Can anyone recommend a fairly efficient way to check if an array contains only numeric keys?

(谁能推荐一种相当有效的方法来检查数组是否仅包含数字键?)

Basically, I want to be able to differentiate between this:

(基本上,我希望能够区分以下两者:)

$sequentialArray = array('apple', 'orange', 'tomato', 'carrot');

and this:

(和这个:)

$assocArray = array('fruit1' => 'apple', 
                    'fruit2' => 'orange', 
                    'veg1' => 'tomato', 
                    'veg2' => 'carrot');
  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have asked two questions that are not quite equivalent:

(您问了两个不完全相同的问题:)

  • 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

    (其次,如何确定数组是否具有从0开始的连续数字键)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...