CKTIS / PHP
Iterator::next — advance to the next element
`Iterator::next()` advances an iterator by one step without returning the element. When iterating manually, check `valid()` before reading the value with `current()`.
Version: PHP 8.3
Syntax
public function Iterator::next(): void
Instance call: $iterator->next();Iterator::next is a public instance method of the Iterator interface. Calling $iterator->next() takes no arguments and changes the position of the same object. In PHP 8.3, the interface method's void return type is tentative. The method is distinct from the global function \next($array), which advances an array's internal pointer and returns the value at the new position, or false if there is no next element.
In PHP 8.3, Iterator is built in, and the example's ArrayIterator is part of SPL, which is always available. Neither requires enabling an optional extension.
For manual iteration, start with rewind(). Check the position with valid() before reading the value with current() or the key with key(). Call next() after processing the element. Once the iterator moves past the last element, valid() returns false; use that result to detect the end, not the element's value or the result of next().
With an Iterator object, foreach calls rewind() at the start, then calls next() and checks valid() as it moves from one iteration to the next. Do not call next() again inside the loop unless you intend to skip elements. A break exits the loop without another automatic advance.
Examples
<?php
$iterator = new \ArrayIterator(['red', 'blue']);
$iterator->rewind();
while ($iterator->valid()) {
echo $iterator->current(), "\n";
$iterator->next();
}
var_dump($iterator->valid());
Result
red blue bool(false)
The example uses SPL's `ArrayIterator`. It prints `red` first and `blue` after the first advance. After the second advance, `valid()` returns `false`, displayed as `bool(false)`.
Related lessons
- PHP · Lesson 61 · Advanced · Version: 2
- PHP · Lesson 63 · Advanced · Version: 2