How to move the internal pointer of an array in PHP?

Every PHP array has an internal pointer that points to one element. You can move it with these functions:

FunctionWhat it does
current()Returns the element where the pointer is now
key()Returns the key of the current element
next()Moves the pointer one step forward
prev()Moves the pointer one step back
reset()Moves the pointer to the first element
end()Moves the pointer to the last element
<?php
$fruits = ["apple", "banana", "cherry"];

echo current($fruits) . "<br>";
echo next($fruits) . "<br>";
echo next($fruits) . "<br>";
echo prev($fruits) . "<br>";
echo reset($fruits) . "<br>";
echo end($fruits);
?>

Output:

Tutorials Class - Output Window

apple
banana
cherry
banana
apple
cherry

When the pointer goes outside the array, next() and prev() return false.


Learn more about the similar topics:
Tutorials
PHP Arrays
PHP Array Functions
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
What are the different PHP functions to sort an array?
PHP’s numerically indexed array begins with which position?
Which PHP function inserts an element to the end of an array?
Which PHP function can be used check if variable is an array?
How many types of arrays are available in PHP?
What is the use of array_chunk() function in PHP?
What is the use of in_array() function in PHP?