What's the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this:
foreach ($an_array as $key => $val) break;
Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?
array_keys
returns an array of keys. Take the first entry. Alternatively, you could callreset
on the array, and subsequentlykey
. The latter approach is probably slightly faster (Thoug I didn't test it), but it has the side effect of resetting the internal pointer.key($an_array)
will give you the first keyedit per Blixt: you should call
reset($array);
beforekey($an_array)
to reset the pointer to the beginning of the array.Interestingly enough, the foreach loop is actually the most efficient way of doing this.
Since the OP specifically asked about efficiency, it should be pointed out that all the current answers are in fact much less efficient than a foreach.
I did a benchmark on this with php 5.4, and the reset/key pointer method (accepted answer) seems to be about 7 times slower than a foreach. Other approaches manipulating the entire array (array_keys, array_flip) are obviously even slower than that and become much worse when working with a large array.
Foreach is not inefficient at all, feel free to use it!
Edit 2015-03-03:
Benchmark scripts have been requested, I don't have the original ones but made some new tests instead. This time I found the foreach only about twice as fast as reset/key. I used a 100-key array and ran each method a million times to get some noticeable difference, here's code of the simple benchmark:
On my php 5.5 this outputs:
reset+key http://3v4l.org/b4DrN/perf#tabs
foreach http://3v4l.org/gRoGD/perf#tabs
If efficiency is not that important for you, you can use
array_keys($yourArray)[0]
in PHP 5.4 (and higher).Examples:
The advantage over solution:
is that you can pass
array_keys($arr)[0]
as a function parameter (i.e.doSomething(array_keys($arr)[0], $otherParameter)
).HTH
To enhance on the solution of Webmut, I've added the following solution:
The output for me on PHP 7.1 is:
If I do this for an array of size 10000, then the results become
The array_keys method times out at 30 seconds (with only 1000 elements, the timing for the rest was about the same, but the array_keys method had about 7.5 seconds).