获取(可能)关联数组中的第一个键? [英] 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;
因此让 $key 包含第一个键,但这似乎效率低下.有人有更好的解决方案吗?
Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?
推荐答案
2019 更新
从 PHP 7.3 开始,有一个名为 array_key_first()
的新内置函数,它将从给定的数组中检索第一个键,而无需重置内部指针.查看文档了解更多信息.
2019 Update
Starting from PHP 7.3, there is a new built in function called array_key_first()
which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info.
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.
只要记住调用reset
,否则你可能会得到数组中的任何一个键.您还可以使用 end
而不是 reset
来获取最后一个键.
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.
如果你想让key得到第一个值,reset
实际上返回它:
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屋!