Home >Backend Development >PHP Tutorial >Teach you how to get the last value in a PHP array

Teach you how to get the last value in a PHP array

巴扎黑
巴扎黑Original
2017-08-04 16:53:511786browse

This article mainly introduces two methods of obtaining the last value of an array in PHP. This article directly gives the implementation code. The code contains comments. Friends in need can refer to it.

The code is as follows:

$array=array(1,2,3,4,5);
echo $array[count($array)-1];//Calculate the length of the array, and then get the last element of the array, if the array The last element in contains a non-numeric key name, and the result may not be as expected
//Applicable to arrays with numeric key names
echo '0c6dc11e160d3b678d68754cc175188a';
echo end($array); //Point the internal pointer of the array to the last unit, applicable to all arrays

Generally speaking, PHP's built-in function end is still the best method. You can test it.

It’s 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 that can 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);  //结果是一维数组
?>

This is the value method of the three functions, directly Valid, choose as needed

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 means that there will no longer be the last value in the original data

The above is the detailed content of Teach you how to get the last value in a PHP array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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