PHP获取数组最后一个元素

一个解决方案是使用end和key的组合:

end()将数组的内部指针提升到最后一个元素,并返回其值。
key()返回当前数组位置的索引元素。
所以,这样的代码的一部分应该做的诀窍:

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

另一种更简单的获取最后一个元素的方法:

<?php
echo $array[count($array) - 1];
?>

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据