← Back to Chapters

PHP Array Traversing Functions

? PHP Array Traversing Functions

ℹ️ Quick Overview

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.

? Key Concepts

  • 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.

? Syntax / Theory

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.

?️ Live Pointer Simulator

Interact with the buttons to see how PHP moves the internal pointer.

Apple
Banana
Cherry
Date
Elderberry
current($fruits) => "Apple"

? Code Example 1: current(), next(), prev()

? View Code Example
// Traversing an indexed array using pointer functions
<?php
$fruits = array("apple", "banana", "cherry", "date");
echo current($fruits);
echo next($fruits);
echo prev($fruits);
?>

? Explanation

current() returns apple. next() advances the pointer to banana, and prev() moves it back to apple.

? Code Example 2: each() and reset()

? View Code Example
// 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);
?>

? Explanation

each() returns the first key-value pair. reset() moves the pointer back to the start, allowing current() to access the first element again.

? Interactive Pointer Flow

apple banana cherry date Pointer moves → next()

? Use Cases

  • Manual navigation through arrays
  • Building custom iterators
  • Accessing first or last elements efficiently
  • Debugging array pointer behavior

✅ Tips & Best Practices

  • Use reset() before traversal to avoid pointer issues
  • Prefer foreach for modern PHP looping
  • Use pointer functions only when fine-grained control is required

? Try It Yourself

  • Create an array of movies and traverse using next() and prev()
  • Use reset() and end() to print first and last elements
  • Compare pointer traversal with a foreach loop