如何检查数组是否定义为键值对? [英] How do I check, if an array is defined as key value pairs?

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

问题描述

我有一个函数,它将数组作为参数。

I have a function, that takes an array as an argument.

function addSearch($arr) { }

如何检查该函数是否仅使用值定义了

How can I check in that function whether the array was defined just with values

array('option1', 'option2', ...);

或作为键值对:

array('option1' => 'First Option', 'option2' => 'Second Option', ...)

我想达到的目标是,您既可以将搜索文件与标签一起传递,也可以只传递搜索字段,在这种情况下,字段名称也会成为标签。

What I like to achive, is that you could either pass the search fileds along with labels, or just the search fields, in which case the field name will also become the label.

所以我需要更改一个数组,该数组的值只是 $ array ['option1'] ='option1';

So I need to change an array, that has just values to $array['option1'] = 'option1';

有什么想法可以实现这一目标吗?

Any ideas how to achive this?

推荐答案

您不知道数组是定义的。两种数组都是同一个东西,它们都有键和值。区别在于无键数组使用自动生成的数字键,而在其他示例中,键显式地指定为字符串。这两个数组是相同的:

You cannot know how an array was defined. Both kinds of arrays are the same thing, they both have keys and values. The difference is that the "keyless array" uses auto-generated numeric keys, while in the other example keys are explicitly given as strings. These two arrays are identical:

array('option1', 'option2')
array(0 => 'option1', 1 => 'option2')

您甚至可以将两者混合使用:

You can even mix both:

array('foo', 'bar' => 'baz', 42 => 'qux')

因此,您真正感兴趣的是键是否为字符串:

Therefore, what you're really interested in is whether the key is a string:

foreach ($options as $key => $value) {
    if (is_string($key)) {
        // string => value pair
    } else {
        // numerically indexed pair
        // note: could still have been explicitly defined, who knows?
    }
}

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

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