PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array contains only numeric keys?
Basically, I want to be able to differentiate between this:
$sequentialArray = array('apple', 'orange', 'tomato', 'carrot');
and this:
$assocArray = array('fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot');
There are many answers already, but here is the method that Laravel relies on within its Arr class:
Source: https://github.com/laravel/framework/blob/5.4/src/Illuminate/Support/Arr.php
This would work too (demo):
Please note that the main point of this answer is to inform you about the existence of
SplFixedArray
and not to encourage you to use Exceptions for these kinds of tests.Speed-wise:
Memory-wise:
You have asked two questions that are not quite equivalent:
Consider which of these behaviours you actually need. (It may be that either will do for your purposes.)
The first question (simply checking that all keys are numeric) is answered well by Captain kurO.
For the second question (checking whether the array is zero-indexed and sequential), you can use the following function:
By using xarray PHP extension
You can do this very fast (about 30+ times faster in PHP 5.6):
Or:
Surely this is a better alternative.