胖鸭 2008-10-06 07:01
浏览 439
已采纳

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

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');

转载于:https://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential

  • 写回答

25条回答 默认 最新

  • 狐狸.fox 2012-11-23 02:51
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(24条)

报告相同问题?

悬赏问题

  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata