phparrays

How to check if PHP 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 "is a list" (contains only numeric keys starting from 0)?

Basically, I want to be able to differentiate between this:

$sequentialArray = [
    'apple', 'orange', 'tomato', 'carrot'
];

and this:

$assocArray = [
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'veg1' => 'tomato',
    'veg2' => 'carrot'
];

Solution

  • Since 8.1 PHP has a simple answer, array_is_list().

    For the legacy code you can use the following function (wrapping it in function_exists() to make it portable):

    if (!function_exists('array_is_list')) {
        function array_is_list(array $arr)
        {
            if ($arr === []) {
                return true;
            }
            return array_keys($arr) === range(0, count($arr) - 1);
        }
    }
    

    And then you can use the this function with any PHP version.

    var_dump(array_is_list([])); // true
    var_dump(array_is_list(['a', 'b', 'c'])); // true
    var_dump(array_is_list(["0" => 'a', "1" => 'b', "2" => 'c'])); // true
    var_dump(array_is_list(["1" => 'a', "0" => 'b', "2" => 'c'])); // false
    var_dump(array_is_list(["a" => 'a', "b" => 'b', "c" => 'c'])); // false