PHP 8.1 : array_is_list()
28, May 2021

array is a very powerful tool in PHP codebase. PHP developers love to (ab)use arrays to solve every problem they encounter. array being very flexible at storing any type of data in any structure is really (not) blessing in PHP projects. Huge bunch of array_* functions are there to help us with all kind of array handling. array_is_list() is new addition to them.


What is list?

in array context, list means an array whose first index is 0 and every index after that increases by +1. So all index must be sequential integers.

So [0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f'] is a list array, as it's index started from 0 and ended on 5, without skipping any numbers.

On the other hand, [0 => 'a', 1 => 'b', 2 => 'c', 4 => 'e', 5 => 'f'] is not a list array, because it skipped index 3. List arrays should not have any "gap" between them.

[1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd'] is not a list array too, because it started from index 1. List array should always start with index 0.


Meet array_is_list()

array_is_list() accepts an array and returns boolean that indicates if provided array is list or not.

so

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


What if we don't define index keys in the array?

If you don't define array keys, PHP automatically assign them as incremental integer.

For example, ['a', 'b'] is actually same as [0 => 'a', 1 => 'b']

So array_is_list() can still work on arrays that do not have index defined.

array_is_list([]); // returns true on empty array
array_is_list(['a']); // returns true
array_is_list(['b', 'c']); // returns true because php automatically assigned index 0 and 1
array_is_list([0 => 'b', 'c']); // returns true because php automatically assigned index 1 to 'c'

Note: array_is_list() accepts only array type. Other array-alike types (iterable, ArrayAccess) won't work on it.


RFC: https://wiki.php.net/rfc/is_list