Traversing arrays in PHP means accessing each element of an array and performing operations on them. PHP provides internal pointer functions such as current(), next(), prev(), reset(), end(), and each() to move through array elements one by one.
current() – Returns the current element.next() – Moves the pointer forward.prev() – Moves the pointer backward.each() – Returns key-value pair and advances pointer.reset() – Moves pointer to first element.end() – Moves pointer to last element.PHP arrays maintain an internal pointer. Traversing functions manipulate this pointer instead of looping directly. These functions are useful when you need manual control over array navigation.
Interact with the buttons to see how PHP moves the internal pointer.
// Traversing an indexed array using pointer functions
<?php
$fruits = array("apple", "banana", "cherry", "date");
echo current($fruits);
echo next($fruits);
echo prev($fruits);
?>
current() returns apple. next() advances the pointer to banana, and prev() moves it back to apple.
// Using each() to fetch key-value pairs and reset() to rewind pointer
<?php
$fruits = array("apple" => 1, "banana" => 2, "cherry" => 3);
print_r(each($fruits));
reset($fruits);
echo current($fruits);
?>
each() returns the first key-value pair. reset() moves the pointer back to the start, allowing current() to access the first element again.
reset() before traversal to avoid pointer issuesforeach for modern PHP loopingnext() and prev()reset() and end() to print first and last elementsforeach loop