简体   繁体   中英

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?

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?
    }
}

this will check if your array is associative

function is_associative($array) {
    return array_values($array) !== $array;
}

Another solution

<?php
function isAssociative($arr)
{
    return array_keys($arr) !== range(0, count($arr) - 1);
}
?>

I have to go with @phranx on this one.

Let's say you have this array('1'=>'Under', '2'=>'Over')

The keys in this array will be evaluated as integers.

The best way is to determine if the keys are key:values pairs is to check if the values of the array are equal to the array itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM