OneBite.Dev - Coding blog in a bite size

Get The Last Element Of Array In PHP

Code snippet for how to Get The Last Element Of Array In PHP with sample and detail explanation

Navigating arrays is a fundamental aspect of managing data within PHP. This brief article specifically demonstrates how to retrieve the last element of an array using PHP.

Code Snippet for Getting the Last Element of an Array in PHP

Here is a simple code snippet that will allow you to retrieve the last element of an array in PHP:

$array = ['one', 'two', 'three', 'four'];
$lastElement = end($array);
echo $lastElement;

If you run this code, it should output:

'four'

Code Explanation for Getting the Last Element of an Array in PHP

In the given PHP code, we start by creating an array called $array containing four elements, i.e., ‘one’, ‘two’, ‘three’, ‘four’.

Then, we use the PHP end() function, which changes the internal pointer of an array to its last element and returns its value. In our case, the final element of the array is the string ‘four’.

$lastElement = end($array);

We pass our array $array as a parameter to end(), and it moves the internal array pointer to the last element of $array, returning its value and assigning it to the variable $lastElement.

To check whether our $lastElement variable indeed contains the value of the last element of our $array, we echo $lastElement in the last line of our code:

echo $lastElement;

When running this PHP code, the terminal will print ‘four’ - the last element in our array - as expected.

This simple technique using the end() function allows you to quickly and efficiently locate the last element of any array in PHP.

php