Dynamically mutable iterator

dev-master 2016-02-05 09:39 UTC

This package is auto-updated.

Last update: 2020-10-05 10:46:17 UTC


Build Status

Iterant is a PHP library that implements the Iterator interface.


  • To append and prepend elements in runtime;
  • To run a callable for each element.
class RenanBr\Iterant implements Iterator
    public function __construct(callable $mapper = null);

    /* Inserts the specified value as the last item of the list.
     * If $target is given, inserts after it. */
    public function append(mixed $value, mixed $target = null): void;

    /* Inserts the specified value as the first item of the list.
     * If $target is given, inserts before it. */
    public function prepend(mixed $value, mixed $target = null): void;

    /* and, evidently, all Iterator methods */
    public function current(): mixed;
    public function key(): int;
    public function next(): void;
    public function rewind(): void;
    public function valid(): bool;


composer require renanbr/iterant


Adding items dynamically

$iterator = new RenanBr\Iterant;
$iterator->prepend('before the first');

foreach ($iterator as $item) {
    if ($item == 'first') {
        $iterator->append('second and half', 'second');
    if ($item == 'third') {
        // insert non catchable items
        $iterator->append('hidden', 'second');
        $iterator->prepend('mystery', 'third');

        $iterator->append('fourth', 'third');
    echo $item . "\n";

/* Result:
 *     before the first
 *     first
 *     second
 *     second and half
 *     third
 *     fourth


You can optionally apply a callback for each element. The sample bellow shows how to get items from a container.

$container = new RenanBr\Sack;
$container->set('first', 'Bob');
$container->set('second', 'John');

$iterator = new RenanBr\Iterant([$container, 'get']);

foreach ($iterator as $item) {
    echo "Hello $item!\n";

 * Result:
 *     Hello Bob!
 *     Hello John!

This sample uses renanbr/sack as ContainerInterface implementation.