PHP 8.6.0 Beta 1 is available for testing

La clase LimitIterator

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Introducción

La clase LimitIterator permite iterar sobre una parte limitada de entidades desde un Iterator .

Sinopsis de la clase

class LimitIterator extends IteratorIterator {
/* Métodos */
public function __construct (Iterator $iterator, int $offset = 0, int $limit = -1)
public function current (): mixed
public function getPosition (): int
public function key (): mixed
public function next (): void
public function rewind (): void
public function seek (int $offset): int
public function valid (): bool
/* Métodos heredados */
public function IteratorIterator::current (): mixed
public function IteratorIterator::key (): mixed
public function IteratorIterator::next (): void
public function IteratorIterator::rewind (): void
public function IteratorIterator::valid (): bool
}

Ejemplos

Ejemplo #1 Ejemplo de uso de LimitIterator

<?php
// Crear un iterador a limitar
$fruits = new ArrayIterator(array(
 'apple',
 'banana',
 'cherry',
 'damson',
 'elderberry'
));
// Bucle sobre los 3 primeros frutos únicamente
foreach (new LimitIterator($fruits, 0, 3) as $fruit) {
 var_dump($fruit);
}
echo "\n";
// Bucle desde el 3o fruto hasta el último
// Nota: la clave comienza en cero para apple
foreach (new LimitIterator($fruits, 2) as $fruit) {
 var_dump($fruit);
}
?>

El ejemplo anterior mostrará:

string(5) "apple"
string(6) "banana"
string(6) "cherry"
string(6) "cherry"
string(6) "damson"
string(10) "elderberry"

Tabla de contenidos

Found A Problem?

Learn How To Improve This PageSubmit a Pull RequestReport a Bug
+add a note

User Contributed Notes 2 notes

up
1
christophg at grenz-bonn dot de
5 years ago
If the inner iterator implements SeekableIterator, LimitIterator uses seek() after rewind() to move to the offset.
up
0
woody dot gilk at gmail dot com
10 months ago
Note that the keys are NOT altered by LimitIterator, so:
$items = new LimitIterator([0 => 'foo', 1 => 'bar', 2 => 'baz'], 1, 1);
// $items is effectively [1 => 'bar']
+add a note

AltStyle によって変換されたページ (->オリジナル) /