Reputation: 464
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?
Upvotes: 2
Views: 7961
Reputation: 1153
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))
Upvotes: 14
Reputation:
function is_associative_array($array) { return (is_array($array) && !is_numeric(implode("", array_keys($array)))); }
Testing the keys works well.
Upvotes: 2
Reputation: 625427
Short answer: no.
Long answer: Associative and indexed arrays are the same type in PHP. Indexed arrays are a subset of associative arrays where:
You can try and detect that if you want by using array_keys(), a sort and comparison with a range() result.
Upvotes: 1
Reputation: 53606
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
Upvotes: 8