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/>';
}
}
The
OutOfBoundsExceptionis thrown when theLimitIteratortries to seek to the starting offset after rewinding, at the very beginning of theforeachloop.If you want to test to see if the seek position is okay, then either
rewind()or manuallyseek()within atry/catchblock.Of course, you could instead wrap your
foreachloop in atry/catchblock.It does not always return
false, only when it is not at a valid positon.The
LimitIteratorin your script, at the point of callingvalid(), has not been told to move anywhere along itself nor the inner iterator. Untilrewind()orseek()has been called, there is no way for it to be at a valid position.