PHP 8.1 – New feature array_is_list()

PHP 8.1 – New feature array_is_list()

batman slapping for not checking a type of array

Added a new check to array to see if it contains only an int based keys in natural order (from 0 to n`). Useful when we want to ensure the array is consistent (untouched) and when we want to serialize an array to json to format of [0, 1, 2] instead of object properties.

This feature doesn’t change PHP’s type system and doesn’t add new type hints.

$x = [1 => 'a', 0 => 'b'];
var_export(array_is_list($x));  // false because keys are out of order
var_export(array_is_list($x));  // true
// Pitfalls of simpler polyfills - NAN !== NAN
$x = ['key' => 2, NAN];
var_export($x === array_values($x));  // false because NAN !== NAN
var_export($x);  // array (0 => NAN)
var_export(array_is_list($x));  // true because keys are consecutive integers starting from 0
array_is_list(new stdClass());  // throws a TypeError
array_is_list(null);  // throws a TypeError

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.

Leave a Comment