2019 Update (2019更新)
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. (从PHP 7.3开始,有一个名为array_key_first()
的新内置函数,该函数将从给定数组中检索第一个键,而无需重置内部指针。) Check out the documentation for more info. (查看文档以获取更多信息。)
You can use reset
and key
: (您可以使用reset
和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. (只要记住要调用reset
,否则您可能会得到数组中的任何键。) You can also use end
instead of reset
to get the last key. (您也可以使用end
而不是reset
来获取最后一个密钥。)
If you wanted the key to get the first value, reset
actually returns it: (如果您希望键获取第一个值,则reset
实际上将其返回:)
$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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…