Home > Backend Development > PHP Tutorial > How Can I Get the Last Element of a PHP Array Without Removing It?

How Can I Get the Last Element of a PHP Array Without Removing It?

Mary-Kate Olsen
Release: 2024-12-07 18:51:12
Original
382 people have browsed it

How Can I Get the Last Element of a PHP Array Without Removing It?

Getting the Last Array Element Without Deletion

This question pertains to an array's last element retrieval without deleting it. While array_pop() provides a simple solution, it removes the targeted element.

Solution:

To achieve this, utilize the end() function. It returns the last element while simultaneously adjusting the array's internal pointer. This can be used as follows:

$myLastElement = end($yourArray);
Copy after login

Special Note:

In PHP versions 7.3.0 and above, array_key_last offers an alternative. It returns the last array key without affecting the internal pointer. To get the last value:

$myLastElement = $yourArray[array_key_last($yourArray)];
Copy after login

The above is the detailed content of How Can I Get the Last Element of a PHP Array Without Removing It?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template