Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Checking if array keys are out of order using array_is_list() in PHP 8.1

Working with arrays, there might come a time when you want to check if the array in question is a list or not. So, how does an array qualifies as a “list”?

An array can be called a list when the keys (must be in form of an integer) are consecutive in nature. Meaning, if the array is an associative array with integer keys, it shouldn’t have missing array offsets, or contains out-of-order keys.

For instance, take the following for example.

$cars = [
    0 => 'BMW',
    1 => 'Tesla',
    2 => 'Audi'
]

Here, we can call the $cars array as a list since the integer keys here are in proper order. But if it’s the following…

$cars = [
    2 => 'BMW',
    0 => 'Tesla',
    1 => 'Audi'
]

…in this case, the $cars array is not a list as the keys are now out of order.

Now, to check if the array is a list or not, we can write our own implementation like so.

function is_list(array $array): bool 
{
    $expectedKey = 0;
    foreach ($array as $i => $_) {
        if ($i !== $expectedKey) { return false; }
        $expectedKey++;
    }
    return true;
}

$cars = [
    2 => 'BMW',
    0 => 'Tesla',
    1 => 'Audi'
]

var_dump(is_list($cars)); // false

…Or if you’re planning to upgrade to PHP 8.1, there’s a function for this that you can use out-of-the-box!

The array_is_list() function

This PR for PHP 8.1 will introduce a function called array_is_list() which can be used for the same purpose I discussed above.

So, if we want to rewrite our previous example with this function, we can do it like so.

$cars = [
    0 => 'BMW',
    1 => 'Tesla',
    2 => 'Audi'
]

var_dump(array_is_list($cars)); // true

And that’s it! This is all this function does.

Caveat

One thing to note here is this function would not work correctly with arrays with keys other than integer for the obvious reasons.

Also, anything other than array passed to array_is_list() would throw in a type error.

array_is_list(new stdClass());  // throws a TypeError
array_is_list(null);  // throws a TypeError
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?