How to Paginate lines in a foreach loop with PHP

A very elegant solution is using a LimitIterator:

$xml = simplexml_load_string($rawxml);
// can be combined into one line
$ids = $xml->xpath('id'); // we have an array here
$idIterator = new ArrayIterator($ids);
$limitIterator = new LimitIterator($idIterator, $offset, $count);
foreach($limitIterator as $value) {
    // ...
}

// or more concise
$xml = simplexml_load_string($rawxml);
$ids = new LimitIterator(new ArrayIterator($xml->xpath('id')), $offset, $count);
foreach($ids as $value) {
    // ...
}

Leave a Comment