PHP tip: LimitIterator

January 25, 2009

If you’ve ever found yourself writing the anti-pattern:

$i = 0;
foreach ($iterable as $element) {
    if ($i >= 5)
        break;

    $element->doStuff();
    $i++;
}

You might be able to make use of PHP’s SPL:

foreach (new LimitIterator($iterable, 0, 5) as $element) {
    $element->doStuff();
}

Leave a Reply