php8.5
Home/ Manual/ language / predefined/ The IteratorAggregate interface

The IteratorAggregate interface

Interface to create an external Iterator.

Intro

Interface to create an external Iterator.

Interfacesynopsis

implements IteratorAggregate extends Traversable { }

Examples

Basic usage

php
<?php

class myData implements IteratorAggregate
{
    public function getIterator(): Traversable
    {
        return new ArrayIterator([
            "key one" => "item one",
            "key two" => "item two",
            "key three" => "item three"
        ]);
    }
}

$obj = new myData();

foreach ($obj as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}

The above example will output something similar to:

output
string(7) "key one"
string(8) "item one"

string(7) "key two"
string(8) "item two"

string(9) "key three"
string(10) "item three"

Getiterator

In this section

Source: language/predefined/iteratoraggregate.xml · from the official PHP manual (php/doc-en)