end: to move the cursor to last element of an array

end(): move the internal pointer to the last element

end() moves an array's internal pointer to its last element and returns that value. The array must be stored in a variable because end() takes the array by reference.

$items = ['red', 'green', 'blue'];
echo end($items);       // blue
echo key($items);       // 2

For ordinary iteration use foreach; end(), reset(), next() and prev() are for explicit pointer navigation.

To move the cursor of internal pointer of an array we can use end() function. This function takes the pointer to last element. Example.
$my_array=array("First One", "Second One", "Third One", "Fourth One", "Fifth One");
end($my_array);
echo current($my_array); // Fifth One 
By using reset() we will take the cursor to first element.
$my_array=array("First One", "Second One", "Third One", "Fourth One", "Fifth One");
end($my_array);
echo current($my_array); // Fifth One 
reset($my_array);
echo current($my_array); //First One 
What happens if the pointer is moved beyond the last element ?
$my_array=array("First One", "Second One", "Third One", "Fourth One", "Fifth One");
while (key($my_array) !== null) {
$key = key($my_array);
$val = current($my_array);
next($my_array); 
echo "$key -> $val <br>"; 
}
end($my_array);
echo current($my_array); // Fifth One 
By using end() we will keep the pointer at the last element of the array.
$my_array=array("First One", "Second One", "Third One", "Fourth One", "Fifth One");

echo current($my_array); // Output : First One 
echo next($my_array); // Output : Second One 
echo next($my_array); // Output : Third One 
echo prev($my_array); // Output : Second One 
echo end($my_array); // Output : Fifth One 
echo reset($my_array); // Output : First One

Example: Traversing an Array in Reverse

$arr = ['apple', 'banana', 'cherry', 'date'];
while ($arr !== []) {
    $value = end($arr);
    echo $value . " ";
    array_pop($arr);
}
// Output: date cherry banana apple

Example: Using end() on an Empty Array

$arr = [];
echo end($arr);  // Output: false

Array REFERENCE


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer