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, orfalseif 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
falseor empty values,next()returnsfalsefor that element, which can be confused with the end of the array. Usekey() !== nullfor 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
falsewhen the pointer moves beyond the last element of the array.
