PHP Arrays: A good way to check if an array is associative or sequential

PHP treats all arrays as associative, so there aren’t any built in functions. Can anyone recommend a fairly efficient way to check if an array contains only numeric keys?

Sollution

<?php
function isAssoc($arr)
{
    return array_keys($arr) !== range(0, count($arr) - 1);
}

var_dump(isAssoc(array('a', 'b', 'c'))); // false
var_dump(isAssoc(array("0" => 'a', "1" => 'b', "2" => 'c'))); // false
var_dump(isAssoc(array("1" => 'a', "0" => 'b', "2" => 'c'))); // true
var_dump(isAssoc(array("a" => 'a', "b" => 'b', "c" => 'c'))); // true

?>

Leave a comment