Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_is_list() function

Reference for PHP array_is_list() (PHP 8.1): check whether an array's keys are 0, 1, 2 and so on in order, with examples for JSON output and validation.

array_is_list() tells you whether an array is a list: its keys are exactly 0, 1, 2, ... in that order, with no gaps and no string keys. It returns true or false. An empty array counts as a list.

It was added in PHP 8.1. Before that, people wrote array_keys($a) === range(0, count($a) - 1), which is slower and clumsier. A common use is deciding whether an array should be written as a JSON array or a JSON object.

PHP
<?php
var_dump(array_is_list(["a", "b"]));      // true
var_dump(array_is_list([1 => "a"]));      // false

Try it

PHP Lists and non-lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Choosing a JSON shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_is_list(array $array): bool
Name Description
$array The array to check.

Return value: true if the keys are the integers 0 to count($array) - 1 in order, otherwise false.

Usage notes

  • Added in PHP 8.1. For older versions you need your own check.
  • Order matters. [1 => "b", 0 => "a"] has the right keys but in the wrong order, so it is not a list.
  • Gaps appear easily. unset(), array_filter() and array_unique() keep the original keys. Fix the result with array_values().
  • JSON: json_encode() writes a list as [...] and anything else as {...}. Checking first helps you predict the shape.
  • Quick: the function stops at the first key that breaks the pattern.
  • Empty array: it returns true, which is also how JSON writes an empty array ([]).
  • Validation: useful for argument checks, such as "this parameter must be a list of strings".