Search code examples
phpforeachspl

object LimitIterator - OutOfBoundsException


How can I write a condition that not to run the foreach below if the object LimitIterator is empty?

$numbers = array(5, 19, 8, 35, 50);

$iterator = new ArrayIterator($numbers);

$limiter = new LimitIterator($iterator, 5, 2);

foreach($limiter as $number)
{
    echo $number.'<br/>';
}

The code above returns this error,

Fatal error: Uncaught exception 'OutOfBoundsException' with message 'Seek position 5 is out of range' in ..
OutOfBoundsException: Seek position 5 is out of range in..

I just don't want to run the foreach if the object LimitIterator is empty.

EDIT:

Why does $limiter->valid(); always return false? I have the code below running on a page on my site,

$numbers = array(5, 19, 8, 35, 50);

$iterator = new ArrayIterator($numbers);

$limiter = new LimitIterator($iterator, 0, 2);

var_dump($limiter->valid());

if ($limiter->valid()) 
{
    foreach($limiter as $number)
    {
        echo $number.'<br/>';
    }
}

Solution

  • The OutOfBoundsException is thrown when the LimitIterator tries to seek to the starting offset after rewinding, at the very beginning of the foreach loop.

    If you want to test to see if the seek position is okay, then either rewind() or manually seek() within a try/catch block.

    try {
        $limiter->rewind();
    } catch (OutOfBoundsException $e) {
        // Do whatever
    }
    

    Of course, you could instead wrap your foreach loop in a try/catch block.


    Why does $limiter->valid(); always return false?

    It does not always return false, only when it is not at a valid positon.

    The LimitIterator in your script, at the point of calling valid(), has not been told to move anywhere along itself nor the inner iterator. Until rewind() or seek() has been called, there is no way for it to be at a valid position.