Check If Array is a List using array_is_list in PHP 8.1

When working with arrays, there might be a case to determine if an array is a list. Since PHP 8.1, array_is_list function can be used to check whether a given array is a list. This means that array should have sequential integer keys which start from 0.

<?php

// Empty array
var_dump(array_is_list([])); // true

// All elements of the same type
var_dump(array_is_list([100, 5, 60])); // true

// Elements of different types
var_dump(array_is_list(['true', 1, false])); // true

// Keys given explicitly
var_dump(array_is_list([0 => 'red', 'green', 2 => 'blue'])); // true

Here are some examples when array is not a list and array_is_list function returns false:

<?php

// An array is not starting from 0
var_dump(array_is_list([1 => 100, 5, 60])); // false

// Incorrect order of keys
var_dump(array_is_list([0 => 100, 2 => 5, 1 => 60])); // false

// Non-integer keys
var_dump(array_is_list([100, 'a' => 5, 60])); // false

// Non-sequential keys
var_dump(array_is_list([100, 2 => 5, 3 => 60])); // false

Leave a Comment

Your email address will not be published.