PHP’s arrays are a mix of dictionaries and lists (i. e. in Python).
Sometimes you have to determine if an array is a list:
1
|
|
or a dictionary:
1 2 3 4 |
|
Unfortunately PHP has no built-in method to do so. One of the good solutions I’ve ran across is to use the array_filter()
on the array’s keys to determine if they’re all integers:
1 2 3 |
|
This function simply compares the number of items which keys are integers to the number of all items in the array. If both are equal the array is indexed.
As a variation one could use is_string()
instead of is_int()
:
1 2 3 |
|
The advantage of this variant is that no additional count($array) is required, so it should be slightly faster than the first variant.
Both examples can easily be modified to return the type of the array: