Warning: Undefined array key "action" in /home/bakers/html/entryreply.php on line 5

Warning: Undefined variable $output in /home/bakers/html/entryreply.php on line 50

Warning: Undefined array key "EntrySubject" in /home/bakers/html/entryreply.php on line 51

Warning: Undefined variable $logintext in /home/bakers/html/entryreply.php on line 97

Warning: Undefined variable $reply_name in /home/bakers/html/entryreply.php on line 103

Warning: Undefined variable $reply_email in /home/bakers/html/entryreply.php on line 104
Perturb.org - interesting technology related things from around the internet

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: 3.239.50.33
To prevent spam please submit by clicking the kitten: