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?
This is the easier way I had ever found. Fast and only two lines of code :-D
You can use
reset
andkey
:It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening.
Just remember to call
reset
, or you may get any of the keys in the array. You can also useend
instead ofreset
to get the last key.If you wanted the key to get the first value,
reset
actually returns it:There is one special case to watch out for though (so check the length of the array first):
You could try
For 2018+
Starting with PHP 7.3, there is an
array_key_first()
function that achieve exactly this:Documentation is available here.
This could also be a solution.
I have tested it and it works.
The best way that worked for me was
array_keys
gets array of keys from initial array and thenarray_shift
cuts from it first element value. You will need PHP 5.4+ for this.