获取第一个关键的(可能)关联数组? [英] Get first key in a (possibly) associative array?
问题描述
什么是确定一个可能的关联数组的第一个键的最佳方式?我首先想到的是刚刚的foreach的数组,然后立刻打破它,就像这样:
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?
推荐答案
You can use reset
and key
:
reset($array);
$first_key = key($array);
这基本上是一样的您最初的code,但有一点开销更少,而且它更明显发生了什么。
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)
这篇关于获取第一个关键的(可能)关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!