PHP

Determine if a PHP Array is a List (PHP 8.1+)

Discover array_is_list() (PHP 8.1+) to check if an array has sequential, 0-indexed integer keys, useful for differentiating between lists and associative arrays.

<?php
// A true list
$list = ['apple', 'banana', 'cherry'];
var_dump(array_is_list($list)); // true

// An empty array is considered a list
$empty_list = [];
var_dump(array_is_list($empty_list)); // true

// An array with non-sequential or non-zero starting keys is not a list
$associative = ['name' => 'Alice', 'age' => 30];
var_dump(array_is_list($associative)); // false

// An array with mixed numeric and string keys is not a list
$mixed_keys = [0 => 'first', 'one' => 'second'];
var_dump(array_is_list($mixed_keys)); // false

// An array with non-zero starting numeric keys is not a list
$non_zero_start = [1 => 'a', 2 => 'b'];
var_dump(array_is_list($non_zero_start)); // false

// An array with sparse numeric keys is not a list
$sparse_keys = [0 => 'a', 2 => 'c'];
var_dump(array_is_list($sparse_keys)); // false
?>
How it works: Introduced in PHP 8.1, array_is_list() determines if an array is a 'list' – meaning it has sequential, 0-indexed integer keys without any gaps, or if it's an empty array. This function is extremely useful for distinguishing between numerically indexed lists and associative arrays, helping developers write more robust code that can handle different array structures correctly, especially when interoperating with JSON which explicitly differentiates between arrays and objects based on this structure.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs