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

巴扎黑
Release: 2023-03-14 16:26:02
Original
1711 people have browsed it

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 '
';
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);  //结果是一维数组
?>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!