PHP Array Operations--getting the last value of an array method _php tips

Source: Internet
Author: User

During the PHP development process, you may often need to retrieve an array to get the last health or value of the array. The cloud-dwelling community here summarizes three methods and describes the limitations of how they are used in some cases, according to their three methods.

<?php 
$array =array (1,2,3,4,5); 
Echo $array [Count ($array) -1];//computes the length of the array and then gets the last element of the array, and if the last element in the array contains a Non-numeric key, the result may be inconsistent with 
the expected//array of the number of key names- 
Echo ' <br> '; 
Echo End ($array);//point the array's internal pointer to the last cell, which applies to all arrays, 
echo ' <br> '; 
Rsort ($array);//The reverse ordering of pairs, if the array contains letters or Chinese characters, the result may not be expected, the most suitable for the number array 
echo $array [0]; 
>

Overall, PHP's built-in function end is the best way to do it. We can test it.

PHP value is easy, you can use the loop traversal, class pointer (personal), but if the last value of the array is also used to traverse the words is not a lot of performance ah??

Here are three ways to get the last value out of the array better:

? 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); The result is a one-dimensional array

This is the three function of the value method, directly valid, on-demand choice

March 31, 2012 Edit: The second method has a disadvantage, the Array_pop () function will be the last number of the original data "out", which is equivalent to the meaning of shearing, the original data will not no longer have the last value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.