In PHP, we primarily use two types of arrays. These two arrays are the index array and associative array. Either of these arrays can be a list.
We consider an array a list if its keys consist of consecutive numbers from 0 to the size of the array minus the value 1. If the keys of an array are 0,1,2,3,4 until the last array index consecutively, then an array is a list.
array_is_list()
methodThe array_is_list()
method will check if an array is a list or not and will return the appropriate boolean value to that effect. Therefore, if the array is not a list, a false
is returned, and if a true
is returned, an array is a list. This function only works on PHP version 8.1 and later.
The syntax of the method is as follows:
array_is_list($array_value)
$array_value
: We’ll use this array to check if it’s a list.The function will return an integer 1
if it evaluates as true and an empty value if it evaluates as false.
The code snippet below shows different arrays which are checked for being a list or not.
<?php//checking if an empty array is a listif(array_is_list([])){echo "true \n";};//check if this index array is a listif(array_is_list(['apple', 2, 3])){echo "true \n";}// The keys are not in the correct order and doesn't start at zeroif(array_is_list([1 => 'apple', 0 => 'orange']) === false){echo "false \n"; // false}// This array contains Non-integer keysif (array_is_list([0 => 'apple', 'foo' => 'bar']) === false){echo "false \n";}// Non-consecutive keysif(array_is_list([0 => 'apple', 2 => 'bar'])=== false){echo "false \n";};?>
Line 4: We’ll use the if
statement to check if an empty array is a list or not and print the value.
Line 9: We check if this index array is a list.
Line 14: We use an array whose keys are not in the correct order and don’t start at zero, then check if it is a list or not.
Line 19: We use the if
statement to check if the array_is_list()
method will evaluate true on Non-integer keys.
Line 24: The array here contains the Non-integer keys.
Therefore, it will not evaluate as a list, and the if
condition will evaluate as false.