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');
I noticed two popular approaches for this question: one using
array_values()
and other usingkey()
. To find out which is faster, I wrote a small program:Output for the program on PHP 5.2 on CentOS is as follows:
Output on PHP 5.3 yielded similar results. Obviously using
array_values()
is much faster.I think the definition of a scalar array will vary by application. That is, some applications will require a more strict sense of what qualifies as a scalar array, and some applications will require a more loose sense.
Below I present 3 methods of varying strictness.
Modification on the most popular answer.
This takes a little more processing, but is more accurate.
To merely check whether the array has non-integer keys (not whether the array is sequentially-indexed or zero-indexed):
If there is at least one string key,
$array
will be regarded as an associative array.One way to approach this is to piggyback on
json_encode
, which already has its own internal method of differentiating between an associative array and an indexed array in order to output the correct JSON.You can do this by checking to see if the first character returned after encoding is a
{
(associative array) or a[
(indexed array).