Home >Backend Development >PHP Tutorial >How Can I Differentiate Between Sequential and Associative Arrays in PHP?

How Can I Differentiate Between Sequential and Associative Arrays in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 16:07:10829browse

How Can I Differentiate Between Sequential and Associative Arrays in PHP?

Identifying Associative or Sequential Arrays in PHP

With PHP's treatment of arrays as associative by default, distinguishing between sequential and associative arrays poses a challenge. This arises from the need to categorize arrays as either "lists" (numeric keys starting from 0) or associative arrays (named keys).

Identifying Sequential Arrays

To determine if an array is sequential, the following function can be employed:

function array_is_list(array $arr)
{
    if ($arr === []) {
        return true;
    }
    return array_keys($arr) === range(0, count($arr) - 1);
}

Using this function, we can differentiate the following arrays:

$arr1 = ['apple', 'orange', 'tomato', 'carrot'];
$arr2 = ['fruit1' => 'apple', 'fruit2' => 'orange', 'veg1' => 'tomato', 'veg2' => 'carrot'];

var_dump(array_is_list($arr1)); // true (sequential array)
var_dump(array_is_list($arr2)); // false (associative array)

Legacy Code and PHP 8.1

For PHP 8.1 and above, the built-in array_is_list() function eliminates the need for the custom function:

var_dump(array_is_list(['a', 'b', 'c'])); // true
var_dump(array_is_list(['1' => 'a', '0' => 'b', '2' => 'c'])); // true
var_dump(array_is_list(['a' => 'a', 'b' => 'b', 'c' => 'c'])); // false

The above is the detailed content of How Can I Differentiate Between Sequential and Associative Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn