PHP: Test for numeric and associative arrays

I wanted to test if a PHP array was associative or numeric. Here are two functions that will work for that.

public function is_assoc_array($array) {
    if (!is_array($array)) { return false; }
    // $array = array() is not associative
    if (sizeof($array) === 0) { return false; }

    return array_keys($array) !== range(0, count($array) - 1);
}
public function is_numeric_array($array) {
    if (!is_array($array)) { return false; }

    $current = 0;
    foreach (array_keys($array) as $key) {
        if ($key !== $current) { return false; }
        $current++;
    }

    return true;
}

Update: I also wrote a test to see if the numeric array is flat.



Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 52.14.88.137
To prevent spam please submit by clicking the kitten: