This post will discuss how to get the last element of an array (without deleting it) in PHP.

1. Using end() function

You can invoke the end() function to get the value at the end of the array. It returns the value present at the end of the array, and false if the array is empty.

Download  Run Code

 
Note that the end() function advances the internal pointer of the array to its last element. If you do not wish to modify the internal array pointer, pass the array as a parameter to a function and call the end() function. This works because the array is passed as a copy rather than a reference.

Download  Run Code

 
This function returns the “value” at the end of the array. To get the key at the end of the array, you can invoke the key() function after making a call to the end() function.

Download  Run Code

2. Using array_key_last() function

As of PHP 7.3.0, array_key_last() function is the recommended way to get the last key of an array. It outperforms the end() function in terms of performance and avoids any side effects, such as moving the internal array pointer.

Download  Run Code

 
The array_key_last() function returns “key” at the end of the array. To get the value at the end of the array, you can use the array’s manual access notation.

Download  Run Code

3. Using array_slice() function

For PHP <= 7.2, you can use the array_slice() function to fetch the last element of an array. It accepts the offset parameter, which denotes the position in the array, and extracts a slice from the array. If the offset is negative, the positioning will start from the array’s end.

Download  Run Code

 
The array_slice() function acts as an efficient alternative to the end() function. However, it returns an array instead of last value. However, it returns an array instead of the last value. array_slice($array, -1)[0] or array_pop(array_slice($array, -1)) can be used to obtain the value.

Download  Run Code

4. Using [] operator

If you have a numerical array, you can access its last element using array’s manual access notation. This only works with numerical arrays, but fails for associate arrays.

Download  Run Code

That’s all about getting the last element of an array in PHP.