PHP 8.1: New array_is_list
function
PHP 8.1 brings a new function array_is_list
, that returns whether a given array is an array with all sequential integers starting from 0.
In other words, this function returns true
if the given array is semantic list of values; an array with all keys are integers, keys start from 0, with no gaps in between.
array_is_list
function returns true
on empty arrays as well.
array_is_list([]); // true
array_is_list([1, 2, 3]); // true
array_is_list(['apple', 2, 3]); // true
array_is_list(['apple', 'orange']); // true
array_is_list([0 => 'apple', 'orange']); // true
array_is_list([0 => 'apple', 1 => 'orange']); // true
Any array with keys not starting from zero, or any array with not all keys are integers in sequential order evaluates to false
:
// Key does not start with 0
array_is_list([1 => 'apple', 'orange']); // false
// Keys are not in order
array_is_list([1 => 'apple', 0 => 'orange']); // false
// Non-integer keys
array_is_list([0 => 'apple', 'foo' => 'bar']); false
// Non-sequential keys
array_is_list([0 => 'apple', 2 => 'bar']); false
array_is_list
Function Synopsis
function array_is_list(array $array): bool {
}
array_is_list
only acceptsarray
parameters. Passing any other type will throw aTypeError
exception.array_is_list
function does not acceptiterable
or other array-like class objects such asArrayAccess
,SPLFixedArray
, etc.array_is_list
is declared in the global namespace.
Polyfill
array_is_list
function can be trivially polyfilled with user-land PHP code:
function array_is_list(array $array): bool {
if (empty($array)) {
return true;
}
$current_key = 0;
foreach ($array as $key => $noop) {
if ($key !== $current_key) {
return false;
}
++$current_key;
}
return true;
}
Backwards Compatibility Impact
array_is_list
is a new function added in PHP 8.1. Unless there is an existing function with the same name in global namespace, there should be no backwards-compatibility issues.
Further, array_is_list
function can be back-ported to almost any PHP version.