Home > Backend Development > PHP Tutorial > How Can I Reliably Determine if a PHP Array is a Sequential List?

How Can I Reliably Determine if a PHP Array is a Sequential List?

Linda Hamilton
Release: 2024-12-20 12:14:09
Original
523 people have browsed it

How Can I Reliably Determine if a PHP Array is a Sequential List?

Differentiating Associative and Sequential PHP Arrays

PHP inherently recognizes all arrays as associative, making it challenging to distinguish between arrays that behave like lists. To resolve this, we explore a reliable method to determine if an array qualifies as a list.

List vs. Associative Arrays

  • List (Sequential Array): Contains only numeric keys starting from 0, forming a sequence.
$sequentialArray = [
    'apple', 'orange', 'tomato', 'carrot'
];
Copy after login
  • Associative Array: Consists of both string and numeric keys, allowing for more versatile data organization.
$assocArray = [
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'veg1' => 'tomato',
    'veg2' => 'carrot'
];
Copy after login

Identifying Lists in PHP 8.1 and Beyond

PHP 8.1 introduced array_is_list() for conveniently checking if an array is a list:

array_is_list($sequentialArray); // true
Copy after login

Legacy Solution for Earlier PHP Versions

To cater to pre-8.1 PHP versions, we can define a custom function:

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

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

By leveraging these methods, developers can effectively distinguish between associative and sequential arrays, enabling more precise and efficient array handling in their PHP applications.

The above is the detailed content of How Can I Reliably Determine if a PHP Array is a Sequential List?. 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