Possible Duplicate:
PHP Arrays: A good way to check if an array is associative or sequential?
Hello :)
I was wondering what is the shortest (best) way to check if an array is
a list:
array('a', 'b', 'c')
or it's an associative array:
array('a' => 'b', 'c' => 'd')
fyi: I need this to make a custom json_encode
function
ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return false. If no element repeats, return false.
function is_assoc($array){
return array_values($array)!==$array;
}
Note that it will also return TRUE if array is indexed but contains holes or doesn't start with 0, or keys aren't ordered. I usually prefer using this function because it gives best possible performance. As an alternative for these cases I prefer this (just keep in mind that it's almost 4 times slower than above):
function is_assoc($array){
return !ctype_digit( implode('', array_keys($array)) );
}
Using ksort()
as Rinuwise commented is a bit slower.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With