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');
Could this be the solution?
The caveat is obviously that the array cursor is reset but I'd say probably the function is used before the array is even traversed or used.
Actually the most efficient way is thus:
This works because it compares the keys (which for a sequential array are always 0,1,2 etc) to the keys of the keys (which will always be 0,1,2 etc).
This function can handle:
the idea is simple: if one of the keys is NOT an integer, it is associative array, otherwise it's sequential.
I compare the difference between the keys of the array and the keys of the result of array_values() of the array, which will always be an array with integer indices. If the keys are the same, it's not an associative array.
answers are already given but there's too much disinformation about performance. I wrote this little benchmark script that shows that the foreach method is the fastest.
Disclaimer: following methods were copy-pasted from the other answers
results:
In my opinion, an array should be accepted as associative if any of its keys is not integer e.g. float numbers and empty string ''.
Also non-sequenced integers has to be seen as associative like (0,2,4,6) because these kind of arrays cannot be used with for loops by this way:
The second part of the function below does check if the keys are indexed or not.It also works for keys with negative values. For example (-1,0,1,2,3,4,5)