How to get last key in an array?
我怎样才能得到数组的最后一个键?
A solution would be to use a combination of end
and key
(quoting) :
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);
Will output :
string 'last' (length=4)
ie the key of the last element of my array.
Although end()
seems to be the easiest, it's not the fastest.
The faster, and much stronger alternative is array_slice()
Strike-out by editor: This claim has not been substantiated and contrary evidence has been mentioned in the comments. If there is any shred of truth to this poster's assertions about speed/efficiency then a benchmark test must be provided.
$last_key = key( array_slice( $array, -1, 1, TRUE ) );
我更喜欢
end(array_keys($myarr))
链接地址: http://www.djcxy.com/p/40542.html
上一篇: 寻找一个好的动态影像解决方案
下一篇: 如何获得数组中的最后一个键?