如何检查 PHP 数组是关联的还是顺序的? [英] How to check if PHP array is associative or sequential?

查看:26
本文介绍了如何检查 PHP 数组是关联的还是顺序的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 = [
    'apple', 'orange', 'tomato', 'carrot'
];

还有这个:

$assocArray = [
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'veg1' => 'tomato',
    'veg2' => 'carrot'
];

推荐答案

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

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

这篇关于如何检查 PHP 数组是关联的还是顺序的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆