During the PHP development process, you may often need to get the last key or value of the array from the retrieved array . Here Bangkejia summarizes three methods and explains the conditions and restrictions on how to use them in some situations.
<?php $array=array(1,2,3,4,5); echo $array[count($array)-1];//计算数组长度,然后获取数组最后一个元素,如果数组中最后一个元素含有非数字键名,结果可能跟预期不符合 //适用于键名为数字的数组 echo '<br>'; echo end($array);//将数组的内部指针指向最后一个单元,适用于所有数组 echo '<br>'; rsort($array);//对数组逆向排序,如果数组中含有字母或汉字,结果可能不符合预期,最适用于数字数组 echo $array[0]; ?>
Generally speaking, PHP’s built-in function end is still the best method. You can test it.
It is easy to get values in PHP. You can use loop traversal and class pointers (personally called them). But if you also use traversal when going to the last value of the array, will it consume a lot of performance? ?
There are three value methods below to better retrieve the last value of the array:
<?PHP $array = array(1,2,4,6,8); echo end($array); ?> <?PHP $array = array(1,2,4,6,8); echo array_pop($array); ?> <?PHP $array = array(1,2,4,6,8); $k = array_slice($array,-1,1); print_r($k); //结果是一维数组 ?>
These are the value methods of the three functions, which are directly effective. Choose according to your needs
Edited on March 31, 2012: The second method has a drawback. The Array_pop() function will "take out" the last number of the original data, which is equivalent to cutting. There will no longer be a last value