Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

php - 获取(可能)关联数组中的第一个键?(Get first key in a (possibly) associative array?)

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. (因此,让$ key包含第一个键,但这似乎效率很低。) Does anyone have a better solution? (有谁有更好的解决方案?)

  ask by Alex S translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 : (您可以使用resetkey :)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...