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?
+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
2009-05-24 01:36:58
Please see my comment below about comparing the original array to its array_values().
grantwparks
2009-07-30 04:10:53
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
2009-05-24 01:50:58
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
2009-07-25 14:14:15
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
2009-07-26 05:51:33
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
2009-07-26 13:40:10