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
Mary-Kate OlsenOriginal
2024-12-07 18:51:12378browse

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);

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)];

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!

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