php 如何获取数组中的最后一个键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2348205/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:08:01  来源:igfitidea点击:

How to get last key in an array?

phparrays

提问by ajsie

How can I get the last key of an array?

如何获取数组的最后一个键?

回答by Pascal MARTIN

A solution would be to use a combination of endand key(quoting):

一个解决方案是使用end(引用)的组合:key

  • end()advances array 's internal pointer to the last element, and returns its value.
  • key()returns the index element of the current array position.
  • end()将 array 的内部指针前进到最后一个元素,并返回它的值。
  • key()返回当前数组位置的索引元素。

So, a portion of code such as this one should do the trick :

因此,像这样的一部分代码应该可以解决问题:

$array = array(
    'first' => 123,
    'second' => 456,
    'last' => 789, 
);

end($array);         // move the internal pointer to the end of the array
$key = key($array);  // fetches the key of the element pointed to by the internal pointer

var_dump($key);

Will output :

将输出:

string 'last' (length=4)

i.e. the key of the last element of my array.

即我的数组的最后一个元素的键。

After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset()on the array to bring the pointer back to the beginning of the array.

完成此操作后,数组的内部指针将位于数组的末尾。正如评论中所指出的,您可能希望reset()在数组上运行以将指针返回到数组的开头。

回答by Tadej Magajna

Although end()seems to be the easiest, it's not the fastest. The faster, and much stronger alternative is array_slice():

虽然end()看起来是最简单的,但它并不是最快的。更快,更强大的替代方案是array_slice()

$lastKey = key(array_slice($array, -1, 1, true));

As the tests say, on an array with 500000 elements, it is almost 7x faster!

正如测试所说,在具有 500000 个元素的数组上,它几乎快了 7 倍!

回答by Rutger van Baren

I prefer

我更喜欢

end(array_keys($myarr))

回答by Patryk Godowski

Since PHP 7.3(2018)there is (finally) function for this: http://php.net/manual/en/function.array-key-last.php

PHP 7.3 (2018) 起(终于) 有此功能:http: //php.net/manual/en/function.array-key-last.php

$array = ['apple'=>10,'grape'=>15,'orange'=>20];
echo array_key_last ( $array )

will output

会输出

orange

回答by Aditya Choudhary

Just use : echo $array[count($array) - 1];

只需使用: echo $array[count($array) - 1];

回答by Ryan Hungate

Dont know if this is going to be faster or not, but it seems easier to do it this way, and you avoid the error by not passing in a function to end()...

不知道这是否会更快,但这样做似乎更容易,并且您可以通过不将函数传递给 end() 来避免错误...

it just needed a variable... not a big deal to write one more line of code, then unset it if you needed to.

它只需要一个变量……再写一行代码没什么大不了的,如果需要,然后取消设置。

$array = array(
    'first' => 123,
    'second' => 456,
    'last' => 789, 
);

$keys = array_keys($array);
$last = end($keys);

回答by mickmackusa

As of PHP7.3you can directly access the last key in (the outer level of) an array with array_key_last()

PHP7.3 开始,您可以使用array_key_last()直接访问(外层)数组中的最后一个键

The definitively puts much of the debate on this page to bed. It is hands-down the best performer, suffers no side effects, and is a direct, intuitive, single-call technique to deliver exactly what this question seeks.

最终将本页上的大部分辩论搁置一旁。它无疑是最佳表现者,没有副作用,并且是一种直接、直观、单次调用的技术,可以准确地提供此问题所寻求的内容。

A rough benchmark as proof: https://3v4l.org/hO1Yf

作为证明的粗略基准:https: //3v4l.org/hO1Yf

array_slice() + key():  1.4
end() + key():         13.7
array_key_last():       0.00015

*test array contains 500000 elements, microtime repeated 100x then averaged then multiplied by 1000 to avoid scientific notation. Credit to @MAChitgarha for the initial benchmarkcommented under @TadejMagajna's answer.

array_slice() + key():  1.4
end() + key():         13.7
array_key_last():       0.00015

*测试数组包含 500000 个元素,微时间重复 100 倍,然后平均然后乘以 1000,以避免使用科学记数法。感谢@MAChitgarha在@TadejMagajna's answer下评论的初始基准

This means you can retrieve the value of the final key without:

这意味着您可以检索最终键的值,而无需:

  1. moving the array pointer (which requires two lines of code) or
  2. sorting, reversing, popping, counting, indexing an array of keys, or any other tomfoolery
  1. 移动数组指针(需要两行代码)或
  2. 排序、反转、弹出、计数、索引键数组或任何其他愚蠢的行为

This function was long overdue and a welcome addition to the array function tool belt that improves performance, avoids unwanted side-effects, and enables clean/direct/intuitive code.

这个函数早就应该出现了,它是数组函数工具带的一个受欢迎的补充,它提高了性能,避免了不需要的副作用,并启用了干净/直接/直观的代码。

Here is a demo:

这是一个演示

$array = ["a" => "one", "b" => "two", "c" => "three"];
if (!function_exists('array_key_last')) {
    echo "please upgrade to php7.3";
} else {
    echo "First Key: " , key($array) , "\n";
    echo "Last Key: " , array_key_last($array) , "\n";
    next($array);                 // move array pointer to second element
    echo "Second Key: " , key($array) , "\n";
    echo "Still Last Key: " , array_key_last($array);
}

Output:

输出:

First Key: a
Last Key: c     // <-- unaffected by the pointer position, NICE!
Second Key: b
Last Key: c     // <-- unaffected by the pointer position, NICE!


Some notes:

一些注意事项:

  • array_key_last()is the sibling function of array_key_first().
  • Both of these functions are "pointer-ignorant".
  • Both functions return nullif the array is empty.
  • Discarded sibling functions (array_value_first()& array_value_last()) also would have offered the pointer-ignorant access to bookend elements, but they evidently failed to garner sufficient votes to come to life.
  • array_key_last()array_key_first()的兄弟函数。
  • 这两个函数都是“指针无知的”。
  • null如果数组为空,两个函数都返回。
  • 丢弃的兄弟函数 ( array_value_first()& array_value_last()) 也可以提供对 bookend 元素的无指针访问,但它们显然未能获得足够的选票来实现。

Here are some relevant pages discussing the new features:

以下是一些讨论新功能的相关页面:

p.s. If anyone is weighing up some of the other techniques, you may refer to this small collection of comparisons: (Demo)

ps 如果有人在权衡其他一些技术,你可以参考这个小的比较集:(Demo

Duration of array_slice() + key():     0.35353660583496
Duration of end() + key():             6.7495584487915
Duration of array_key_last():          0.00025749206542969
Duration of array_keys() + end():      7.6123380661011
Duration of array_reverse() + key():   6.7875385284424
Duration of array_slice() + foreach(): 0.28870105743408
Duration of array_slice() + key():     0.35353660583496
Duration of end() + key():             6.7495584487915
Duration of array_key_last():          0.00025749206542969
Duration of array_keys() + end():      7.6123380661011
Duration of array_reverse() + key():   6.7875385284424
Duration of array_slice() + foreach(): 0.28870105743408

回答by codaddict

Try using array_popand array_keysfunction as follows:

尝试使用array_poparray_keys函数,如下所示:

<?php

$array = array(
    'one' => 1,
    'two' => 2,
    'three' => 3
);

echo array_pop(array_keys($array)); // prints three

?>

回答by Hilary Okoro

As of PHP >= 7.3 array_key_last()is the best way to get the last key of any of an array. Using combination of end(), key()and reset()just to get last key of an array is outrageous.

从 PHP >= 7.3 开始,array_key_last()是获取任何数组的最后一个键的最佳方法。使用end(),key()和 的组合reset()来获取数组的最后一个键是令人发指的。

$array = array("one" => bird, "two" => "fish", 3 => "elephant");
$key = array_key_last($array);
var_dump($key) //output 3

compare that to

将其与

end($array)
$key = key($array)
var_dump($key) //output 3
reset($array)

You must reset array for the pointer to be at the beginning if you are using combination of end()and key()

如果您使用end()key()

回答by Hilary Okoro

I would also like to offer an alternative solution to this problem.

我还想为这个问题提供一个替代解决方案。

Assuming all your keys are numeric without any gaps, my preferred method is to count the array then minus 1 from that value (to account for the fact that array keys start at 0.

假设你所有的键都是没有任何间隙的数字,我的首选方法是对数组进行计数,然后从该值减去 1(考虑到数组键从 0 开始的事实。

$array = array(0=>'dog', 1=>'cat');

$lastKey = count($array)-1;
$lastKeyValue = $array[$lastKey];

var_dump($lastKey);
print_r($lastKeyValue);

This would give you:

这会给你:

int(1) cat

int(1) 猫