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, orfalseif 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 booleanfalse.
๐ 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
falseif the array contains no elements. -
Use
end()when you need to perform reverse array traversals or retrieve the last item efficiently.
