PHP Iterables

In PHP, an iterable is an object that can be iterated over using a foreach loop. An iterable can be an array, an object that implements the Traversable interface, or any other object that can be used with the foreach loop.

Here’s an example of using an array as an iterable:

$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
    echo $number . "<br>";
}

In this example, the $numbers variable is an array of integers. We use a foreach loop to iterate over each element in the array and print it out.

We can also use objects as iterables. Here’s an example:

class MyIterable implements IteratorAggregate {
    private $items = [];
    
    public function __construct($items) {
        $this->items = $items;
    }
    
    public function getIterator() {
        return new ArrayIterator($this->items);
    }
}
$myIterable = new MyIterable([1, 2, 3, 4, 5]);
foreach ($myIterable as $item) {
    echo $item . "<br>";
}

In this example, we define a MyIterable class that implements the IteratorAggregate interface. The MyIterable class has a private $items property that holds an array of items, and a getIterator() method that returns an ArrayIterator object that can be used to iterate over the items in the array.

We create an object of the MyIterable class with an array of integers, and use a foreach loop to iterate over each item in the iterable and print it out.

In summary, iterables in PHP are objects that can be iterated over using a foreach loop. An iterable can be an array, an object that implements the Traversable interface, or any other object that can be used with the foreach loop. We can use iterables to loop over collections of data and perform operations on each item in the collection.