PHP: is_flat_array()

PHP supports numeric and associative arrays. PHP's numeric arrays do not have to be sequential, and I wanted a test for that.

function is_flat_array($array) {
    if (!is_array($array)) { return false; }

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

        $current++;
    }

    return true;
}

I wrote up all the test cases I could think of:

var_dump(is_flat_array(array(1, 2, 3)));                // True
var_dump(is_flat_array(array()));                       // True
var_dump(is_flat_array(array('foo' => 'bar')));         // False
var_dump(is_flat_array(array(0 => 3, 'foo' => 'bar'))); // False
var_dump(is_flat_array(array(0 => 3, 1 => 3, 2 => 3))); // True
var_dump(is_flat_array(array(0 => 3, 2 => 3, 3 => 3))); // False
var_dump(is_flat_array("foo"));                         // False

See also: Test for numeric and associative arrays



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

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