一个解决方案是使用end和key的组合:
end()将数组的内部指针提升到最后一个元素,并返回其值。
key()返回当前数组位置的索引元素。
所以,这样的代码的一部分应该做的诀窍:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?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); ?> |
输出:
1 |
string 'last' (length=4) |
另一种更简单的获取最后一个元素的方法:
1 2 3 |
<?php echo $array[count($array) - 1]; ?> |