Current Location: Home> Latest Articles> How to use end() to get the last element of an array

How to use end() to get the last element of an array

M66 2025-05-14

In PHP, the end() function is a very practical built-in function that points a pointer inside an array to the last element of the array and returns the value of that element. We usually use it to get the last value in an array, regardless of the size of the array.

Basic usage of end() function

PHP's end() function can change the pointer inside the array and return the last element in the array. When using the end() function, the pointer of the array moves toward the last element of the array, so it returns the last value in the array. If the array is empty, the end() function returns FALSE .

Here is a simple example:

 <?php
$array = [1, 2, 3, 4, 5];
$lastElement = end($array);
echo $lastElement;  // Output: 5
?>

In this example, end($array) returns the last element 5 in the array $array .

end() function and array pointer

The end() function not only returns the value of the last element, but also changes the pointer of the array to point to the last element. This means that if you then use the current() function, it will return the last element of the array:

 <?php
$array = [10, 20, 30, 40];
end($array);  // Point the pointer to the last element
echo current($array);  // Output: 40
?>

Use end() to get the last element of the associative array

The end() function is not only suitable for index arrays, it is also suitable for associative arrays. Whether the key of the array is a string or an integer, end() can return the last element.

 <?php
$assocArray = [
    "first" => "Apple",
    "second" => "Banana",
    "third" => "Cherry"
];
$lastElement = end($assocArray);
echo $lastElement;  // Output: Cherry
?>

In this example, we use end() to get the last value "Cherry" in the associative array $assocArray .

Things to note

  1. If the array is empty, the end() function returns FALSE . Therefore, it is recommended to check if the array is empty before using end() .

  2. end() will change the pointer of the array pointer. If you do not want to affect the pointer of the array, you can save the pointer position before using end() :

 <?php
$array = [1, 2, 3, 4];
$pointerPosition = key($array);  // Get the current pointer position
end($array);  // Get the last element
echo current($array);  // Output: 4
reset($array);  // Restore the pointer to the original position
?>

Summarize

The end() function is a simple and efficient way to get the last element of an array in PHP. Whether it is a normal index array or an associative array, it can help us easily get the last element. When working with an array, be careful that it changes the pointer position of the array, so in some cases, functions such as key() and reset() may be required to manage pointers.