Question
In PHP, arrays can contain either numeric or string keys, and there is no separate built-in array type for lists versus associative maps in older PHP versions. What is an efficient way to check whether an array behaves like a list—that is, whether it contains only numeric keys starting at 0 in order?
For example, how can I distinguish between these two arrays?
$sequentialArray = [
'apple', 'orange', 'tomato', 'carrot'
];
$assocArray = [
'fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot'
];
Short Answer
By the end of this page, you will understand how PHP array keys work, how to tell whether an array is sequential or associative, and which approaches are best in modern and older PHP versions. You will also see practical examples, common mistakes, and how this check is used in real applications.
Concept
PHP uses one array type for both:
- Lists: values stored with numeric keys in order, usually starting at
0 - Associative arrays: values stored with named keys
That means this is valid in PHP:
$items = ['a', 'b', 'c'];
and so is this:
$items = ['first' => 'a', 'second' => 'b'];
Internally, both are arrays.
The difference is in the keys.
A sequential array (often called a list) usually has keys like this:
[0, 1, 2, 3]
An associative array has keys like this:
['name', 'email', 'role']
or even numeric keys that are not a continuous sequence:
[ => , => ]
Mental Model
Think of a PHP array like a set of labeled storage boxes.
- A sequential array is like boxes on a shelf labeled
0,1,2,3with no missing numbers. - An associative array is like boxes labeled
fruit1,fruit2,veg1,veg2.
If the labels are perfect shelf positions starting at 0, it is a list.
If the labels are custom names, or the numbers skip around, it is associative for practical purposes.
Another way to think about it:
- List = “a row of items”
- Associative array = “a lookup table”
Your check is really asking:
Are these values arranged in a clean row, or are they stored by custom labels?
Syntax and Examples
Modern PHP: array_is_list()
If you are using PHP 8.1 or later, use this:
$sequentialArray = ['apple', 'orange', 'tomato', 'carrot'];
$assocArray = [
'fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot'
];
var_dump(array_is_list($sequentialArray)); // true
var_dump(array_is_list($assocArray)); // false
This is the best option because it is:
- readable
- built into PHP
- designed for exactly this purpose
Older PHP versions
If array_is_list() is not available, a common approach is:
function is_list_array(array ):
{
() === (, () - );
}
Step by Step Execution
Consider this function:
function is_list_array(array $array): bool
{
if ($array === []) {
return true;
}
return array_keys($array) === range(0, count($array) - 1);
}
$data = ['apple', 'orange', 'tomato'];
$result = is_list_array($data);
var_dump($result);
Here is what happens step by step:
-
$datais created:['apple', 'orange', 'tomato']PHP automatically gives it these keys:
[, , ]
Real World Use Cases
1. Choosing how to encode data for JSON
When sending data to a frontend or API, you may need to know whether something should be treated like a list or an object-like map.
$data = ['apple', 'orange'];
This behaves like a collection of values.
But this:
$data = ['first' => 'apple', 'second' => 'orange'];
behaves more like labeled fields.
2. Validating API input
Suppose an endpoint expects a list of user IDs:
[12, 18, 25]
You may reject input like:
['admin' => 12, 'editor' => 18]
because it is not the expected shape.
3. Processing form or configuration data
Some configuration values are key/value pairs:
[
'host' => ,
=>
]
Real Codebase Usage
In real projects, developers rarely check array type just for curiosity. They usually do it because the code must branch into different behavior.
Common patterns
Guard clauses
Reject invalid input early:
function processIds(array $ids): void
{
if (!array_is_list($ids)) {
throw new InvalidArgumentException('Expected a list of IDs.');
}
foreach ($ids as $id) {
// Process each ID
}
}
Validation
Frameworks and service classes often validate not just values, but also structure.
function validateTags(array $tags): bool
{
if (!array_is_list($tags)) {
return false;
}
foreach ( ) {
(!()) {
;
}
}
;
}
Common Mistakes
1. Assuming numeric keys always mean a list
This is wrong:
$array = [2 => 'apple', 3 => 'orange'];
These are numeric keys, but it is not a sequential list starting at 0.
2. Forgetting gaps in keys
Broken assumption:
$array = [0 => 'apple', 2 => 'orange'];
This is not a list because key 1 is missing.
3. Using isset($array[0]) as the only test
Broken example:
function isListWrong(array $array): bool
{
return isset($array[0]);
}
Why it is wrong:
- it only checks one key
Comparisons
| Approach | PHP Version | Good For | Notes |
|---|---|---|---|
array_is_list($array) | 8.1+ | Modern projects | Best choice: built-in, readable, accurate |
array_keys($array) === range(0, count($array) - 1) | Older PHP | Compatibility | Common fallback, but handle empty arrays carefully |
| Loop through keys manually | Any | Performance-sensitive custom logic | More verbose, useful if you want full control |
isset($array[0]) | Any | Almost never sufficient | Not a real list check |
Associative vs sequential
| Type |
|---|
Cheat Sheet
Quick rule
A PHP array is a list if its keys are exactly:
0, 1, 2, ..., n-1
with no gaps and in order.
Best modern solution
array_is_list($array)
- Available in PHP 8.1+
- Returns
truefor sequential arrays - Returns
falsefor associative or non-sequential arrays
Older PHP fallback
function is_list_array(array $array): bool
{
if ($array === []) {
return true;
}
return array_keys($array) === range(0, count($array) - 1);
}
Examples
FAQ
How do I check if an array is associative in PHP?
A common approach is to check whether it is not a list:
$isAssociative = !array_is_list($array);
In older PHP versions, use a custom helper instead.
Is there a built-in PHP function for checking list arrays?
Yes. In PHP 8.1 and later, use:
array_is_list($array)
Are arrays with numeric keys always sequential?
No. Numeric keys like [1 => 'a', 2 => 'b'] are not sequential lists if they do not start at 0.
Does an empty array count as a list?
Usually yes. It contains no invalid keys, so it is generally treated as a valid empty list.
What is the difference between associative and sequential arrays in PHP?
A sequential array has keys 0 through n-1 in order. An associative array uses custom keys such as strings, or numeric keys that are not a continuous sequence.
Why does this matter when working with JSON or APIs?
Because your code may need to treat a collection of items differently from a key/value object structure. Validation and transformation often depend on that distinction.
What should I use in older PHP versions before 8.1?
Mini Project
Description
Build a small PHP utility that inspects several arrays and reports whether each one is a sequential list or an associative array. This is useful for understanding how PHP treats array keys and for practicing reusable helper functions that can be used in validation or data processing code.
Goal
Create a script that checks multiple arrays and prints whether each one is a list or associative.
Requirements
- Write a function that returns whether an array is a sequential list.
- Treat an empty array as a valid list.
- Test the function with at least four different arrays.
- Print a readable label for each test case.
- Include one example with numeric keys that are not sequential.
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.