How to get the last value of php array

PHPz
Release: 2023-05-05 22:31:06
Original
1597 people have browsed it

In PHP, if you want to get the last value in an array, there are many ways to do it. Let’s introduce them one by one below.

Method 1: Use the end() function

The end() function can move the "internal pointer" to the last element of the array and return the element. A code example using this method is as follows:

<?php
$fruits = array('apple', 'orange', 'banana', 'grape');
echo end($fruits);
?>
Copy after login

When this code is executed, "grape" will be output because this value is the last element in the array $fruits.

It should be noted that using the end() function will move the "internal pointer" to the last element of the array, so if you want to access the elements in the array again, you need to move the "internal pointer" to the array first the beginning of.

Method 2: Use the array_pop() function

The array_pop() function can pop the last element of the array and return the element. Therefore, you can use this function to directly get the last element in the array. A code example using this method is as follows:

<?php
$fruits = array('apple', 'orange', 'banana', 'grape');
echo array_pop($fruits);
?>
Copy after login

When this code is executed, "grape" will also be output.

It should be noted that using the array_pop() function will pop the last element of the array and reduce the length of the array by 1. If you wish to preserve the original array, you can copy the array before using this function.

Method 3: Use the count() function

The count() function can return the number of elements in the array. Combined with the array subscript, you can get the last element in the array. A code example using this method is as follows:

<?php
$fruits = array('apple', 'orange', 'banana', 'grape');
echo $fruits[count($fruits)-1];
?>
Copy after login

When this code is executed, "grape" will also be output.

It should be noted that this method needs to first obtain the length of the array through the count() function, and then obtain the last element through the array subscript. Therefore, if the array is empty, an error may occur.

To sum up, the above are three ways to get the last element in a PHP array. Each method has its advantages and disadvantages. You should choose the appropriate method according to the actual situation.

The above is the detailed content of How to get the last value of php array. For more information, please follow other related articles on the PHP Chinese website!

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