Home >Backend Development >PHP Tutorial >How Can I Distinguish Between Sequential and Associative Arrays in PHP?
In PHP, arrays are inherently associative, lacking built-in mechanisms to differentiate between numeric keys starting from 0 (sequential arrays) and arbitrary string keys (associative arrays). This distinction can be crucial for various programming scenarios.
To determine if an array is sequential, you can leverage the newly introduced array_is_list() function in PHP 8.1. However, for older PHP versions, a custom function can provide a practical alternative:
function array_is_list(array $arr) { if ($arr === []) { return true; } return array_keys($arr) === range(0, count($arr) - 1); }
This function checks if the array is empty or if its keys are a continuous sequence of numbers starting from 0. If both conditions are met, the array is considered sequential.
To illustrate the functionality of the array_is_list() function:
var_dump(array_is_list([])); // true var_dump(array_is_list(['a', 'b', 'c'])); // true var_dump(array_is_list(["0" => 'a', "1" => 'b', "2" => 'c'])); // true var_dump(array_is_list(["1" => 'a', "0" => 'b', "2" => 'c'])); // false var_dump(array_is_list(["a" => 'a', "b" => 'b', "c" => 'c'])); // false
The above is the detailed content of How Can I Distinguish Between Sequential and Associative Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!