CKTIS / PHP
LimitIterator
Expose a window of an Iterator by zero-based traversal position, preserving original keys.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
new LimitIterator($iterator, $offset, $limit)Expose a window of an Iterator by zero-based traversal position, preserving original keys. The offset is a number of positions, not an array key. A limit of -1 means no upper count. In PHP 8.4 rewinding a zero-length window over ArrayIterator raises OutOfBoundsException. Use it to bound a lazy or infinite source.
$src=new ArrayIterator([10=>"A",20=>"B",30=>"C"]);
$part=new LimitIterator($src,1,1);
$chunk=iterator_to_array($part);
try{iterator_to_array(new LimitIterator($src,0,0));}catch(OutOfBoundsException $e){$zero=get_class($e);}
echo json_encode([$chunk,$zero]);
[{"20":"B"},"OutOfBoundsException"]
Examples
<?php
$src=new ArrayIterator([10=>"A",20=>"B",30=>"C"]);
$part=new LimitIterator($src,1,1);
$chunk=iterator_to_array($part);
try{iterator_to_array(new LimitIterator($src,0,0));}catch(OutOfBoundsException $e){$zero=get_class($e);}
echo json_encode([$chunk,$zero]);
Result
[{"20":"B"},"OutOfBoundsException"]