php 获取(可能)关联数组中的第一个键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1028668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get first key in a (possibly) associative array?
提问by Alex S
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 数组,然后立即打破它,像这样:
foreach ($an_array as $key => $val) break;
Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?
因此让 $key 包含第一个键,但这似乎效率低下。有没有人有更好的解决方案?
回答by Blixt
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. Check out the documentationfor more info.
从PHP 7.3开始,有一个新的内置函数被调用array_key_first(),它将从给定的数组中检索第一个键,而无需重置内部指针。查看文档以获取更多信息。
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 endinstead of resetto get the last key.
请记住调用reset,否则您可能会获得数组中的任何键。您也可以使用end代替reset来获取最后一个键。
If you wanted the key to get the first value, resetactually 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)
回答by troelskn
array_keysreturns an array of keys. Take the first entry. Alternatively, you could call reseton the array, and subsequently key. The latter approach is probably slightly faster (Thoug I didn't test it), but it has the side effect of resetting the internal pointer.
array_keys返回一个键数组。获取第一个条目。或者,您可以调用reset数组,然后调用key. 后一种方法可能稍微快一些(虽然我没有测试它),但它具有重置内部指针的副作用。
回答by Webmut
Interestingly enough, the foreach loop is actually the most efficient way of doing this.
有趣的是,foreach 循环实际上是最有效的方法。
Since the OP specifically asked about efficiency, it should be pointed out that all the current answers are in fact much less efficient than a foreach.
由于 OP 专门询问了效率,因此应该指出,所有当前的答案实际上都比 foreach 效率低得多。
I did a benchmark on this with php 5.4, and the reset/key pointer method (accepted answer) seems to be about 7 times slower than a foreach. Other approaches manipulating the entire array (array_keys, array_flip) are obviously even slower than that and become muchworse when working with a large array.
我用 php 5.4 对此做了一个基准测试,重置/键指针方法(接受的答案)似乎比 foreach 慢 7 倍。操纵整个阵列的其他方法(array_keys,array_flip)明显更慢比,并成为多用大阵工作时更糟糕。
Foreach is not inefficient at all, feel free to use it!
Foreach 一点也不低效,放心使用吧!
Edit 2015-03-03:
编辑 2015-03-03:
Benchmark scripts have been requested, I don't have the original ones but made some new tests instead. This time I found the foreach only about twice as fast as reset/key. I used a 100-key array and ran each method a million times to get some noticeable difference, here's code of the simple benchmark:
已请求基准脚本,我没有原始脚本,而是进行了一些新测试。这次我发现 foreach 的速度只有 reset/key 的两倍左右。我使用了一个 100 键的数组并运行了每个方法一百万次以获得一些明显的差异,这是简单基准测试的代码:
$array = [];
for($i=0; $i < 100; $i++)
$array["key$i"] = $i;
for($i=0, $start = microtime(true); $i < 1000000; $i++) {
foreach ($array as $firstKey => $firstValue) {
break;
}
}
echo "foreach to get first key and value: " . (microtime(true) - $start) . " seconds <br />";
for($i=0, $start = microtime(true); $i < 1000000; $i++) {
$firstValue = reset($array);
$firstKey = key($array);
}
echo "reset+key to get first key and value: " . (microtime(true) - $start) . " seconds <br />";
for($i=0, $start = microtime(true); $i < 1000000; $i++) {
reset($array);
$firstKey = key($array);
}
echo "reset+key to get first key: " . (microtime(true) - $start) . " seconds <br />";
for($i=0, $start = microtime(true); $i < 1000000; $i++) {
$firstKey = array_keys($array)[0];
}
echo "array_keys to get first key: " . (microtime(true) - $start) . " seconds <br />";
On my php 5.5 this outputs:
在我的 php 5.5 这输出:
foreach to get first key and value: 0.15501809120178 seconds
reset+key to get first key and value: 0.29375791549683 seconds
reset+key to get first key: 0.26421809196472 seconds
array_keys to get first key: 10.059751987457 seconds
reset+key http://3v4l.org/b4DrN/perf#tabs
foreach http://3v4l.org/gRoGD/perf#tabs
重置+密钥http://3v4l.org/b4DrN/perf#tabs
foreach http://3v4l.org/gRoGD/perf#tabs
回答by jimyi
key($an_array)will give you the first key
key($an_array)会给你第一把钥匙
edit per Blixt: you should call reset($array);before key($an_array)to reset the pointer to the beginning of the array.
按 Blixt 编辑:您应该在调用reset($array);之前key($an_array)将指针重置为数组的开头。
回答by Stopper
You could try
你可以试试
array_keys($data)[0]
回答by ivanaugustobd
回答by Sergiy Sokolenko
list($firstKey) = array_keys($yourArray);
回答by Martin Vseticka
If efficiency is not that important for you, you can use array_keys($yourArray)[0]in PHP 5.4 (and higher).
如果效率对您来说不是那么重要,您可以array_keys($yourArray)[0]在 PHP 5.4(及更高版本)中使用。
Examples:
例子:
# 1
$arr = ["my" => "test", "is" => "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "my"
# 2
$arr = ["test", "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "0"
# 3
$arr = [1 => "test", 2 => "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "1"
The advantage over solution:
优于解决方案:
list($firstKey) = array_keys($yourArray);
is that you can pass array_keys($arr)[0]as a function parameter (i.e. doSomething(array_keys($arr)[0], $otherParameter)).
是您可以array_keys($arr)[0]作为函数参数传递(即doSomething(array_keys($arr)[0], $otherParameter))。
HTH
HTH
回答by Pupil
Please find the following:
请找到以下内容:
$yourArray = array('first_key'=> 'First', 2, 3, 4, 5);
$keys = array_keys($yourArray);
echo "Key = ".$keys[0];
回答by Hamidreza
$myArray = array(
2 => '3th element',
4 => 'first element',
1 => 'second element',
3 => '4th element'
);
echo min(array_keys($myArray)); // return 1

