JochenJung JochenJung - 11 months ago 54
PHP Question

How do I check, if an array is defined as key value pairs?

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', ...);

or as key-value pairs:

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.

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

Any ideas how to achive this?

Answer Source

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?