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

时间:2017-07-28
本文章向大家介绍PHP如何获取数组最后的一个键,需要的朋友可以参考一下。

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

  • end() 将数组的内部指针前进到最后一个元素,并返回其值。
  • key() 返回当前数组位置的索引元素。

因此,像这样的代码的一部分应该做的伎俩:

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

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

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