开发者

object LimitIterator - OutOfBoundsException

开发者 https://www.devze.com 2023-03-19 04:27 出处:网络
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);

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 o开发者_如何学运维bject 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/>';
    }
}


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.


Surely, if it's empty, the foreach will be a no-op.

If you insist, you can check that the first element is valid, as alex demonstrated:

$limiter->valid()

but this should be completely unnecessary.

If neither of these approaches "work" for you, then something else is wrong.


Perhaps the real problem here is that you are not checking that the underlying container actually has seven elements to iterate.

I don't know enough about LimitIterator to be sure, but my experience with C++ iterators is that once you go beyond the reasonable bounds of the underlying container, all bets are off. Perhaps this is why $limiter->valid() is "not working" for you?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号