Determine whether an array is associative (hash) or not

Solution 1:

Pulled right out of the kohana framework.

public static function is_assoc(array $array)
{
    // Keys of the array
    $keys = array_keys($array);

    // If the array keys of the keys match the keys, then the array must
    // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
    return array_keys($keys) !== $keys;
}

Solution 2:

This benchmark gives 3 methods.

Here's a summary, sorted from fastest to slowest. For more informations, read the complete benchmark here.

1. Using array_values()

function($array) {
    return (array_values($array) !== $array);
}

2. Using array_keys()

function($array){
    $array = array_keys($array); return ($array !== array_keys($array));
}

3. Using array_filter()

function($array){
    return count(array_filter(array_keys($array), 'is_string')) > 0;
}

Solution 3:

PHP treats all arrays as hashes, technically, so there is not an exact way to do this. Your best bet would be the following I believe:

if (array_keys($array) === range(0, count($array) - 1)) {
   //it is a hash
}