旧行李 2008-10-06 07:01 采纳率: 25%
浏览 229
已采纳

如何检查 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

  • 写回答

24条回答 默认 最新

  • 关注

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

报告相同问题?

悬赏问题

  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding