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?
-
2I sense something wrong in your design. Why would you want to do this?Randell– Randell2009-07-26 05:13:21 +00:00Commented Jul 26, 2009 at 5:13
-
It's not an uncommon need, especially when writing more generic, non application-specific code.grantwparks– grantwparks2012-04-02 06:36:55 +00:00Commented Apr 2, 2012 at 6:36
-
possible duplicate of PHP Arrays: A good way to check if an array is associative or sequential?Gordon– Gordon2012-06-19 17:57:23 +00:00Commented Jun 19, 2012 at 17:57
5 Answers
My short answer: YES
Quicker and easier, IF you make the assumption that a "non-associative array" is indexed starting at 0:
if ($original_array == array_values($original_array))
3 Comments
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. :)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
1 Comment
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.