PHP

โญ๏ธ PHP end() Function: Advancing Array Pointer to the End

The end() function in PHP advances an array's internal pointer to its final element and returns the value of that last element.

  • Return Value: end() returns the value of the last element in the array, or false if the array is empty.

๐Ÿ› ๏ธ Basic Usage & Pointer Positioning

You can instantly jump to the last element of an array using end() regardless of where the current pointer is situated:

PHP
$fruits = ["Apple", "Pear", "Banana"];

// Jump directly to the last element
$lastFruit = end($fruits);

echo $lastFruit;       // Outputs: Banana
echo current($fruits);  // Outputs: Banana

๐ŸŽฏ Practical Use Case: Fetching the Last Key & Value

Combining end() with key() allows you to quickly inspect the final key and value of an associative array:

PHP
$user = [
    "user_id" => 101,
    "username" => "johndoe",
    "role" => "admin"
];

// Move pointer to the end and capture the last element
$lastValue = end($user);
$lastKey   = key($user);

echo "Last Key: " . $lastKey . " | Last Value: " . $lastValue;
// Outputs: Last Key: role | Last Value: admin

๐Ÿ“‹ Key Rules & Behaviors

  • 1. Moves to Last Position: It updates the internal pointer to point directly to the final key/value pair.
  • 2. Passed by Reference: Like other array pointer functions, end(&$array) modifies the state of the original array variable.
  • 3. Empty Array Handling: When executed on an empty array, end() returns boolean false.

๐Ÿ“Š Boundary Pointer Functions Comparison

Function Target Position Modifies Pointer? Return Value
reset() First element โœ… Yes First element value (or false)
end() Last element โœ… Yes Last element value (or false)
  • ๐Ÿ“ Short Summary

  • end() advances the internal pointer directly to the final element of an array.
  • It returns the value of the last element or false if the array contains no elements.
  • Use end() when you need to perform reverse array traversals or retrieve the last item efficiently.