PHP Generators vs Iterator objects

In PHP, generators and iterator objects both provide ways to iterate over data, but they work differently. When a generator function is called, it returns a Generator object that implements the Iterator interface, making it behave like an iterator with some limitations.

Iterator Interface Methods

The Iterator interface defines the following abstract methods −

  • Iterator::current — Return the current element
  • Iterator::key — Return the key of the current element
  • Iterator::next — Move forward to next element
  • Iterator::rewind — Rewind the Iterator to the first element
  • Iterator::valid — Checks if current position is valid

A generator acts as a forward-only iterator object and provides methods to manipulate its state, including sending and receiving values.

Generator as Iterator

The following example shows a generator function that yields lines from a file. The generator object can be traversed using foreach loops and iterator methods like current() and next(). However, since generators are forward-only iterators, calling rewind() throws an exception after the generator has started −

Note: Create a file named "test.txt" with some content for this example to work.
<?php
function filegenerator($name) {
    $fileHandle = fopen($name, 'r');
    while ($line = fgets($fileHandle)) {
        yield trim($line);
    }
    fclose($fileHandle);
}

$name = "test.txt";
$file = filegenerator($name);

// Traverse using foreach
foreach ($file as $line) {
    echo $line . "
"; } // Try to rewind (will cause an error) try { $file->rewind(); echo $file->current(); } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ?>
PHP User Defined Functions
PHP Function Arguments
PHP Variable Functions
PHP Internal (Built-in) Functions
PHP Anonymous functions
PHP Arrow Functions
Error: Cannot rewind a generator that was already run

Generator vs Custom Iterator Comparison

Feature Generator Custom Iterator
Memory Usage Low (lazy evaluation) Higher (stores all data)
Rewindable No (forward-only) Yes (can rewind)
Implementation Simple (function + yield) Complex (class + methods)
Performance Better for large datasets Good for small datasets

Simple Generator Example

Here's a basic example demonstrating generator iterator methods −

<?php
function numbers() {
    yield 1;
    yield 2;
    yield 3;
}

$gen = numbers();

echo "Current: " . $gen->current() . "
"; echo "Key: " . $gen->key() . "
"; echo "Valid: " . ($gen->valid() ? 'true' : 'false') . "
"; $gen->next(); echo "After next - Current: " . $gen->current() . "
"; ?>
Current: 1
Key: 0
Valid: true
After next - Current: 2

Conclusion

Generators provide a memory-efficient way to create iterators but are forward-only. Use generators for large datasets or when you don't need rewinding. For full iterator control with rewind capability, implement a custom Iterator class.

Updated on: 2026-03-15T09:11:05+05:30

624 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements