PHP

⏩ PHP next() Function: Moving Array Pointer Forward

The next() function in PHP advances the internal pointer of an array by one element and returns the value of that element.

  • Return Value: next() returns the value of the array element in the next position that's pointed to by the internal array pointer, or false if there are no more elements.

πŸ› οΈ Basic Usage & Pointer Advancement

By default, an array pointer starts at the first element. Calling next() moves it to the subsequent element:

PHP
$fruits = ["Apple", "Pear", "Banana"];

// Initial state (pointer at "Apple")
echo current($fruits); // Outputs: Apple

// Move pointer forward
$nextFruit = next($fruits);

echo $nextFruit;        // Outputs: Pear
echo current($fruits); // Outputs: Pear

πŸ”„ Manual Array Traversal

You can combine next() with current() or key() to manually iterate through an array:

PHP
$colors = ["Red", "Green", "Blue"];

do {
    echo key($colors) . " => " . current($colors) . "<br>";
} while (next($colors) !== false);

/*
Output:
0 => Red
1 => Green
2 => Blue
*/

πŸ“‹ Key Rules & Behaviors

  • 1. Moves Before Returning: Unlike current() which only inspects the active position, next() shifts the pointer first, then returns the new value.
  • 2. End of Array Behavior: Moving past the last element sets the pointer to an invalid state and returns false.
  • 3. Boolean False Ambiguity: If an array contains boolean false or empty values, next() returns false for that element, which can be confused with the end of the array. Use key() !== null for strict checks.

πŸ“Š Pointer Navigation Functions Comparison

Function Pointer Direction Modifies Pointer? Return Value
current() / pos() None (Current) ❌ No Current element value
next() Forward (+1) βœ… Yes Next element value (or false)
prev() Backward (-1) βœ… Yes Previous element value (or false)
  • πŸ“ Short Summary

  • next() advances the internal array pointer to the next element and returns its value.
  • It directly alters the internal pointer state of the array passed to it.
  • It returns false when the pointer moves beyond the last element of the array.