Current Location: Home> Latest Articles> PHP end() Function to Move Array Pointer to Last Element and Return Its Value

PHP end() Function to Move Array Pointer to Last Element and Return Its Value

M66 2025-10-30

PHP end() Function to Move Array Pointer to Last Element and Return Its Value

In PHP, the end() function can be used to move the internal pointer of an array to the last element and return its value. If the array is empty, it returns NULL.

Using the end() Function to Point to the Last Element of an Array

To move the internal pointer to the last element of an array, you can use the following code:


end($array);

This function moves the internal pointer to the last element of the array and returns its value. If the array is empty, it will return NULL.

Example:


$array = ["foo", "bar", "baz"];

echo end($array); // Output: "baz"

Returning the Element's Value (If Successful)

If the internal pointer is successfully moved to the last element, the end() function will return its value. If not, it will return NULL.

Example:


$array = ["foo", "bar", "baz"];

if (end($array) !== null) {
    echo "The internal pointer is at the last element: " . end($array);
} else {
    echo "The array is empty.";
}

Important Notes

  • The end() function does not modify the array itself; it only moves the internal pointer.
  • If the array is empty, the end() function will return NULL.
  • You can use the reset() function to reset the internal pointer to the first element before moving it.

By using the end() function, PHP developers can easily manipulate the array's pointer and work with the last element. We hope this article is helpful to you. For more PHP tips, keep following related tutorials.