Determining Associative vs Sequential Arrays in PHP
PHP maintains all arrays as associative, prompting the need for alternative methods to distinguish between associative and sequential arrays, particularly those containing only numerical keys starting from 0.
Solution: array_is_list() Function
PHP 8.1 introduces the array_is_list() function, providing a straightforward solution:
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
Custom Function for Legacy Code:
If working with legacy code that does not support PHP 8.1, the following custom function can be employed:
function array_is_list(array $arr) { if ($arr === []) { return true; } return array_keys($arr) === range(0, count($arr) - 1); }
This function achieves the same functionality as the array_is_list() function, making it portable across different PHP versions.
The above is the detailed content of How Can I Distinguish Between Associative and Sequential Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!