Home > Backend Development > PHP Tutorial > PHP array operation - method to get the last value of the array, php array_PHP tutorial

PHP array operation - method to get the last value of the array, php array_PHP tutorial

WBOY
Release: 2016-07-13 09:57:22
Original
838 people have browsed it

PHP array operation - method to get the last value of the array, php array

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.

<&#63;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]; 
&#63;>
Copy after login

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:

<&#63;PHP
$array = array(1,2,4,6,8);
echo end($array);
&#63;> 

<&#63;PHP
$array = array(1,2,4,6,8);
echo array_pop($array);
&#63;> 

<&#63;PHP
$array = array(1,2,4,6,8);
$k = array_slice($array,-1,1);
print_r($k);  //结果是一维数组
&#63;> 
Copy after login

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/983997.htmlTechArticlePHP array operation - method to get the last value of the array, php array PHP development process, you may often need to The retrieved array needs to obtain the last key or value of the array. Here to help the guest house...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template