PHP Iterables

In PHP, an iterable is any data structure that can be traversed with a foreach loop. This includes arrays and objects that implement the Traversable interface.

Types of Iterables

  • Arrays: Standard PHP arrays can be traversed using foreach.
  • Objects: Objects that implement the Traversable interface can also be iterated.

Using Arrays as Iterables

<?php
$fruits = ["apple", "banana", "orange"];

foreach ($fruits as $fruit) {
    echo "$fruit\n";
}
?>

Output:

apple
banana
orange

Using Objects as Iterables

<?php
class MyCollection implements Iterator {
    private $items = [];
    private $currentIndex = 0;

    public function add($item) {
        $this->items[] = $item;
    }

    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]);
    }
}

$collection = new MyCollection();
$collection->add("Item 1");
$collection->add("Item 2");
$collection->add("Item 3");

foreach ($collection as $item) {
    echo "$item\n";
}
?>

Output:

Item 1
Item 2
Item 3

Summary of Iterables

Iterables are a powerful feature in PHP that allow for easy traversal of data structures. By implementing the Iterator interface, custom objects can also become iterable, enhancing the flexibility of your code.