Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether an array is associative (hash) or not

Tags:

arrays

php

hash

I'd like to be able to pass an array to a function and have the function behave differently depending on whether it's a "list" style array or a "hash" style array. E.g.:

myfunc(array("One", "Two", "Three")); // works
myfunc(array(1=>"One", 2=>"Two", 3=>"Three")); also works, but understands it's a hash

Might output something like:

One, Two, Three
1=One, 2=Two, 3=Three

ie: the function does something differently when it "detects" it's being passed a hash rather than an array. Can you tell I'm coming from a Perl background where %hashes are different references from @arrays?

I believe my example is significant because we can't just test to see whether the key is numeric, because you could very well be using numeric keys in your hash.

I'm specifically looking to avoid having to use the messier construct of myfunc(array(array(1=>"One"), array(2=>"Two"), array(3=>"Three")))

like image 897
Tom Auger Avatar asked May 13 '11 19:05

Tom Auger


1 Answers

Pulled right out of the kohana framework.

public static function is_assoc(array $array)
{
    // Keys of the array
    $keys = array_keys($array);

    // If the array keys of the keys match the keys, then the array must
    // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
    return array_keys($keys) !== $keys;
}
like image 86
Matt Whittingham Avatar answered Oct 19 '22 22:10

Matt Whittingham