LimitIterator

LimitIterator is a concrete class that limits the range of another iterator that it composes.

Examples

In the example belowe we limit the range of ArrayIterator to the first four items.

<?php
// Create an iterator to be limited
$fruits = new ArrayIterator(array(
    'apple',
    'banana',
    'cherry',
    'damson',
    'elderberry'
));

// Loop over first three fruits only
foreach (new LimitIterator($fruits, 0, 3) as $fruit) {
    var_dump($fruit);
}

echo "\n";

In the next example we start the iterator at the third element. Since no end of range is give, it will iterator to the end of the collection

<?php
// Loop over first three fruits only
foreach (new LimitIterator($fruits, 2) as $fruit) {
    var_dump($fruit);
}

echo "\n";

/* Output:
 *  string(6) "cherry"
 *  string(6) "damson"
 *  string(10) "elderberry"
 */

LimitIterator can be used with recursive iterators. In the example with start with the second element (counting from 0) in the “flattened” recursive array and return the next four elements in the recursive iteration

<?php
$array = array(
  "Hello", // Level 1
   array(
    "World" // Level 2
   ),
   array(
    "How", // Level 2
    array(
      "are", // Level 3
      "you" // Level 3
    )
   ),
 "doing?" // Level 1
);

// Create our Recursive data structure
$recursiveIterator = new RecursiveArrayIterator($array);

// Create our recursive iterator
$recursiveIteratorIterator = new RecursiveIteratorIterator($recursiveIterator);
// Create a limit iterator
$limitIterator = new LimitIterator($recursiveIteratorIterator, 2, 4);

// Iterate
foreach ($limitIterator as $key => $value) {
    $innerIterator = $limitIterator->getInnerIterator();
    echo 'Depth: ' .$innerIterator->getDepth() . '' . PHP_EOL;
    echo 'Key: ' .$key . '' . PHP_EOL;
    echo 'Value: ' .$value . '' . PHP_EOL;
}