Get first key in a (possibly) associative array?

2019-01-01 08:05发布

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?

标签: php arrays
19条回答
君临天下
2楼-- · 2019-01-01 08:20

This is the easier way I had ever found. Fast and only two lines of code :-D

$keys = array_keys($array);
echo $array[$keys[0]];
查看更多
美炸的是我
3楼-- · 2019-01-01 08:21

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.

If you wanted the key to get the first value, reset actually returns it:

$first_value = reset($array);

There is one special case to watch out for though (so check the length of the array first):

$arr1 = array(false);
$arr2 = array();
var_dump(reset($arr1) === reset($arr2)); // bool(true)
查看更多
梦该遗忘
4楼-- · 2019-01-01 08:22

You could try

array_keys($data)[0]
查看更多
永恒的永恒
5楼-- · 2019-01-01 08:22

For 2018+

Starting with PHP 7.3, there is an array_key_first() function that achieve exactly this:

$array = ['foo' => 'lorem', 'bar' => 'ipsum'];
echo array_key_first($array); // 'foo'

Documentation is available here.

查看更多
其实,你不懂
6楼-- · 2019-01-01 08:22

This could also be a solution.

$first_key = current(array_flip($array));

I have tested it and it works.

查看更多
步步皆殇っ
7楼-- · 2019-01-01 08:24

The best way that worked for me was

array_shift(array_keys($array))

array_keys gets array of keys from initial array and then array_shift cuts from it first element value. You will need PHP 5.4+ for this.

查看更多
登录 后发表回答