How to get the last element of an array without deleting it?

Try end:

$myLastElement = end($yourArray);

Note that this doesn’t just return the last element of the passed array, it also modifies the array’s internal pointer, which is used by current, each, prev, and next.

For PHP >= 7.3.0:

If you are using PHP version 7.3.0 or later, you can use array_key_last, which returns the last key of the array without modifying its internal pointer. So to get the last value, you can do:

$myLastElement = $yourArray[array_key_last($yourArray)];

Leave a Comment