沃梦达 / 编程问答 / php问题 / 正文

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

How to check if PHP array is associative or sequential?(如何检查 PHP 数组是关联数组还是顺序数组?)

本文介绍了如何检查 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 数组是关联数组还是顺序数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何检查 PHP 数组是关联数组还是顺序数组?

基础教程推荐