array_is_list

Advertisement

With the release of PHP 8.1, a new addition emerges: the array_is_list function. This function serves as a validator, determining whether a provided array conforms to the semantic structure of a list.

Specifically, it examines if the array exclusively contains integer keys, beginning at 0 and following a sequential progression without any gaps.

When invoked, array_is_list evaluates these criteria, returning a boolean true if the array aligns with this sequential and non-interrupted integer key pattern. Effectively, it identifies arrays structured akin to a definitive list, ensuring all keys are integers starting from 0, maintaining a continuous sequence.

Understanding array_is_list Understanding array_is_list

This function takes an array as its parameter and returns a boolean value (true or false) indicating whether the provided array conforms to the expected sequential integer key structure of a list.

Here’s the basic syntax of array_is_list:

bool array_is_list(array $array)
  • $array : The $array value is used to check for sequential integer key structure of a list.

Top ↑

Practical Examples Practical Examples

Let’s delve into practical examples to illustrate how array_is_list can be applied in various scenarios.

Example 1: Empty Array Example 1: Empty Array

An empty array is considered a list because it has no elements to check for key order or continuity.

$emptyArray = [];
$isEmptyList = array_is_list($emptyArray); // Result: true
(Note: This function returns true for empty arrays)

Top ↑

Example 2: Valid List Array Example 2: Valid List Array

The array contains values and keys starting from 0, making it a list.

$array2 = ['apple', 2, 3];
$result2 = array_is_list($array2); // Returns true

Top ↑

Example 3: Non-integer keys Example 3: Non-integer keys

The presence of a non-integer keys (‘a’,’b’,’c’) in the array prevents it from being considered a list.

$nonSeqArray = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$isListNonSeq = array_is_list($nonSeqArray); // Result: false

The presence of a non-integer key (‘foo’) in the array prevents it from being considered a list.

$array = [0 => 'apple', 'foo' => 'bar'];
$result = array_is_list($array); // Returns false

Top ↑

Example 5: The keys are not in the correct order Example 5: The keys are not in the correct order

Though keys exist starting from 0 and 1, they are not in sequential order (0, 1) making it not a list.

$array5 = [1 => 'apple', 0 => 'orange'];
$result5 = array_is_list($array5); // Returns false

Top ↑

Example 5: The array does not start at 0 Example 5: The array does not start at 0

The array does not start with key 0, breaking the consecutive key sequence, thus not a list.

$array4 = [1 => 'apple', 'orange'];
$result4 = array_is_list($array4); // Returns false

Leave a Reply