tags:

views:

984

answers:

5

Is there a php function that someone can use to automatically detect if an array is an associative or not, apart from explictly checking the array keys?

+1  A: 

Check out the discussions at is_array.

Alan Haggai Alavi
+7  A: 

quoted from the official site:

The indexed and associative array types are the same type in PHP,

So the best solution I can think of is running on all the keys, or using array_keys,implode,is_numeric

Itay Moav
Please see my comment below about comparing the original array to its array_values().
grantwparks
A: 

Short answer: no.

Long answer: Associative and indexed arrays are the same type in PHP. Indexed arrays are a subset of associative arrays where:

  • The keys are only integers;
  • They range from 0 to N-1 where N is the size of the array.

You can try and detect that if you want by using array_keys(), a sort and comparison with a range() result.

cletus
+2  A: 
+3  A: 
grantwparks
I feel I have to continue because other answers that take longer are being voted up.One does not have to examine the keys. array_values() returns an integer-indexed array, thus if one compares the array in question with its array_values() and they are equal, the original array is a 0 based, integer indexed array. It is the shortest, slickest way. Try it out.
grantwparks
I agree, arrays that are not indexed *continuously starting at `0`* should be considered associative, since they can't be traversed reliably with the typical `for ($x++)` pattern. Hence this test is probably the best to use. It becomes sort of a philosophical debate though, as PHP arrays simply aren't one or the other. :)
deceze
I was just trying to pass on the quickest/slickest way I found to determine if the indices are 0 thru N without any kind of explicit inspection of the keys.<p>I _love_ PHP arrays.
grantwparks