tags:

views:

1788

answers:

4

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?

+5  A: 

array_keys returns an array of keys. Take the first entry. Alternatively, you could call reset on the array, and subsequently key. The latter approach is probably slightly faster (Thoug I didn't test it), but it has the side effect of resetting the internal pointer.

troelskn
Just a (late) note for future readers of this: The latter approach is not just "slightly" faster. There's a big difference between iterating an entire array, storing every key in another newly created array, and requesting the first key of an array as a string.
Blixt
+3  A: 

key($an_array) will give you the first key

edit per Blixt: you should call reset($array); before key($an_array) to reset the pointer to the beginning of the array.

jimyi
Remember that the pointer of the array may not be at the first element, see my answer.
Blixt
+13  A: 

You can use reset and key:

reset($array);
$first_key = key($array);

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 use end instead of reset to get the last key.

Blixt
A: 

Actually, a dictionary has no logical order. Dictionaries or associative arrays are key-value-pairs where the key is used to lookup the value (instead of a numerical index like with arrays). There's no logical order in a key-value-pair set, hence there's no first or last key. However, the underlaying implementation often uses an ordered array and iteration methods so that dictionaries can be (de)serialized. I'm not sure how the PHP handles it, but generally you shouldn't rely on any specific order in a dictionary.

Andreas
I'm more or less checking whether or not the array is associative, and if it's not, I need the first numeric index. I'm fairly certain this is a PHP-centric issue, as many other languages only have numeric arrays or the first index is always 0.
Shadow