Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Iterator::rewind — return an iterator to the start

`foreach` calls `Iterator::rewind()` before its first `valid()` check. Whether that call positions the iterator at its start depends on the implementation.

Version: PHP 8.3

Syntax

public function rewind(): void

Iterator::rewind is a public instance method with no parameters and a void return type. Call $it->rewind() to position the iterator at its first element, if there is one. It does not return that element. When iterating manually, check valid() before reading the value with current() or the key with key(). For an empty iterator, valid() returns false.

When foreach starts on an object implementing Iterator, PHP calls rewind() before the first valid() check. After the loop body, if iteration continues, next() advances the iterator and valid() checks the new position. Ending the loop does not call rewind(). With ArrayIterator, advancing it manually beforehand does not change where a new loop starts.

Do not assume every iterator can be traversed again. Generator::rewind() runs the generator through its first yield; it does nothing if the generator is already there and throws an Exception if it has advanced beyond that point. To start a loop at an iterator's current position, wrap it in NoRewindIterator: foreach still calls rewind(), but the wrapper does not forward the call to the inner iterator.

The iterator method is distinct from rewind($stream), which repositions a file stream, and reset($array), which resets an array's internal pointer.

Examples

<?php
$items = new ArrayIterator(['a' => 'alpha', 'b' => 'beta']);

$items->next();
echo $items->current(), "\n";

$items->rewind();
echo $items->current(), "\n";

$items->next();
foreach ($items as $key => $value) {
    echo $key, '=', $value, "\n";
}

Result

beta
alpha
a=alpha
b=beta

`next()` first moves to `beta`, and the explicit `rewind()` returns to `alpha`. Another `next()` moves back to `beta`, but `foreach` starts with `a=alpha` because it calls `rewind()` itself.

Related lessons

  • PHP · Lesson 61 · Advanced · Version: 2
  • PHP · Lesson 63 · Advanced · Version: 2

Sources