array_is_list()
Checks if an array is a list.
An array is considered a list if its keys consist of consecutive numbers from 0 to count($array)-1.
This is a polyfill for the PHP function array_is_list(), added in PHP 8.1.
No Hooks.
Returns
true|false
. true
- the array is a list, false
- it is not.
Usage
array_is_list( $arr );
- $arr(array) (required)
- The array to check.
Examples
#1 Example of using array_is_list()
array_is_list( [] ); // true array_is_list( [ 'apple', 2, 3 ] ); // true array_is_list( [ 0 => 'apple', 'orange' ] ); // true // The array does not start with 0 array_is_list( [ 1 => 'apple', 'orange' ] ); // false // The array keys are not in order array_is_list( [ 1 => 'apple', 0 => 'orange' ] ); // false // The array keys are not integers array_is_list( [ 0 => 'apple', 'foo' => 'bar' ] ); // false // Non-sequential keys array_is_list( [ 0 => 'apple', 2 => 'bar' ] ); // false
Notes
Changelog
Since 6.5.0 | Introduced. |
array_is_list() array is list code WP 6.8.1
function array_is_list( $arr ) { if ( ( array() === $arr ) || ( array_values( $arr ) === $arr ) ) { return true; } $next_key = -1; foreach ( $arr as $k => $v ) { if ( ++$next_key !== $k ) { return false; } } return true; }