What are iterators

Iterators are objects in programming that allow for sequential access to elements in a collection without exposing the underlying structure of that collection. They enable the iteration over complex data structures like arrays, lists, and more, making it easier to manipulate data by providing a simple interface for traversal.

In PHP, iterators provide a standard way of traversing collections, allowing developers to build custom iterator classes or use built-in iterator classes. Understanding iterators is essential in creating efficient and maintainable code.

<?php class MyIterator implements Iterator { private $items = []; private $currentIndex = 0; public function __construct($items) { $this->items = $items; } public function current() { return $this->items[$this->currentIndex]; } public function key() { return $this->currentIndex; } public function next() { ++$this->currentIndex; } public function rewind() { $this->currentIndex = 0; } public function valid() { return isset($this->items[$this->currentIndex]); } } $items = [1, 2, 3, 4, 5]; $iterator = new MyIterator($items); foreach ($iterator as $key => $value) { echo "Key: $key; Value: $value\n"; } ?>

Iterators PHP Iterators Programming Data Structures