How to check if PHP array is associative or sequential?

PHP treats all arrays as associative, so there aren't any built in functions. 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');

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
  • 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.

    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(array('a', 'b', 'c'))); // false
    var_dump(isAssoc(array("0" => 'a', "1" => 'b', "2" => 'c'))); // false
    var_dump(isAssoc(array("1" => 'a', "0" => 'b', "2" => 'c'))); // true
    var_dump(isAssoc(array("a" => 'a', "b" => 'b', "c" => 'c'))); // true
    

    To merely check whether the array has non-integer keys (not whether the array is sequentially-indexed or zero-indexed):

    function has_string_keys(array $array) {
      return count(array_filter(array_keys($array), 'is_string')) > 0;
    }
    

    If there is at least one string key, $array will be regarded as an associative array.


    当然这是一个更好的选择。

    <?php
    $arr = array(1,2,3,4);
    $isIndexed = array_values($arr) === $arr;
    
    链接地址: http://www.djcxy.com/p/4922.html

    上一篇: PHP和枚举

    下一篇: 如何检查PHP数组是关联还是顺序?