How to Get Last Element of Array in PHP?

How to Get Last Element of Array in PHP?

In PHP, you may often need to access the last element of an array. This guide demonstrates a straightforward way to accomplish this task efficiently. Let's delve into the steps to get the last element of an array in PHP.

To obtain the last element of a PHP array, you can use the end() function. Here's a simple example:

// Sample PHP array
$data = [10, 20, 30, 40, 50];

// Use end() to retrieve the last element
$lastElement = end($data);

// Display the last element
echo $lastElement;

In this example, we begin with a PHP array named $data, which contains a series of values. We utilize the end() function to access the last element of the array.

The end() function moves the internal pointer of the array to the last element and returns that element.

The output will be the last element of the array, which, in this case, is 50.

By following this example, you can effectively obtain the last element of a PHP array using the end() function.