如何获取数组中的最后一个键? [英] How to get last key in an array?

查看:42
本文介绍了如何获取数组中的最后一个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I get the last key of an array?

推荐答案

一个解决方案是结合使用 结束key (引用) :

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

  • end() 将 array 的内部指针前进到最后一个元素,并返回它的值.
  • 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.

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

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);

将输出:

string 'last' (length=4)

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

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

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

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.

这篇关于如何获取数组中的最后一个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆