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
Release: 2024-12-15 16:07:10
Original
828 people have browsed it

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);
}
Copy after login

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)
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template