array_is_list
Tells you whether an array has consecutive integer keys starting at zero.
array_is_list(array $array): bool- Added in PHP 8.1.0
Parameters
| Parameter | Type | Description |
|---|---|---|
$array | array | The array being evaluated. |
Return value
booltrue if the array's keys are the integers 0 to count($array) - 1 in order, or if it is empty; false otherwise.
Errors
Passing a non-array argument throws a TypeError.
Before PHP 8.1 people wrote array_keys($a) === range(0, count($a) - 1), which allocates two arrays, or $a === array_values($a), which is correct but wasteful: it builds a copy of the whole array and then compares it element by element. Prefer the built-in.
Example
When to use it
- Decide whether an incoming decoded JSON payload was an array or an object.
- Guard an API response so a filtered collection still encodes as a JSON array.
- Validate that a variadic or nested argument really is a positional list before iterating by index.
Frequently asked questions
Does array_is_list return true for an empty array?
Yes. An empty array satisfies the rule vacuously and json_encode writes it as [].
How do I turn an array back into a list?
Call array_values() on it, which discards the keys and renumbers from 0. That is the standard fix after array_filter or unset leaves gaps.
What is the difference between array_is_list and checking array_keys === range(...)?
They give the same answer, but array_is_list is a single native check with no allocation, while the range() version builds two temporary arrays. array_is_list is also available only from PHP 8.1.
More examples
Keys must be in order, not just present
$reversed holds the keys 0 and 1 but stores them in the wrong order, so it is not a list. array_values() rebuilds it in insertion order, which makes it one.
<?php
$inOrder = [0 => 'a', 1 => 'b'];
$reversed = [1 => 'b', 0 => 'a'];
var_dump(array_is_list($inOrder));
var_dump(array_is_list($reversed));
var_dump(array_is_list(array_values($reversed)));
print_r(array_keys($reversed));Telling a JSON array from a JSON object
The third case is the interesting one: a JSON object with the string keys "0" and "1" decodes to integer keys 0 and 1, so PHP reports it as a list even though the source was an object.
<?php
foreach (['[1,2,3]', '{"a":1}', '{"0":1,"1":2}'] as $json) {
$decoded = json_decode($json, true);
$kind = array_is_list($decoded) ? 'list' : 'map';
echo $json, ' -> ', $kind, "\n";
}
Discussion