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

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

问题描述

PHP将所有数组作为关联,所以没有任何内置的功能。谁能推荐一个非常有效的方法来检查,如果一个数组只包含数字键?

基本上,我希望能够这样区分:

  $ sequentialArray =阵列('苹果','橙','番茄','胡萝卜');

和这样的:

  $ assocArray =阵列('fruit1'=>苹果,
                    fruit2'=> '橙子',
                    veg1'=> '番茄',
                    veg2'=> '胡萝卜');


解决方案

您已要求不太相当于两个问题:


  • 首先,如何确定一个数组是否只有数字键

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

考虑哪些你确实需要这些行为。 (这可能是要么将你的目的做的。)

第一个问题(简单地检查所有键都是数字)是通过九郎队长回答得很好。

对于第二个问题(检查数组是否是零索引和顺序),可以使用下面的函数:

函数isAssoc($ ARR)
{
    !返回array_keys($ ARR)==范围(0,计数($ ARR) - 1);
}后续代码var_dump(isAssoc(阵列('A','B','C'))); //假
的var_dump(isAssoc(阵列(0=>'一',1=>'B',2=>的'c'))); //假
的var_dump(isAssoc(阵列(1=>'一',0=>'B',2=>的'c'))); //真
后续代码var_dump(isAssoc(阵列(A=>A,B=>'B',C=>'C'))); //真

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($arr)
{
    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

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

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