Skip to content

Getting Started: 6. Iterating And Filtering

Daniele Orlando edited this page Nov 8, 2023 · 4 revisions

Iterations can be performed without interrupting the fluent flow.

->each()

iterates the current context (after a query or an add/append/prepend operation).

$book->query('//chapter')
        ->each(function($i, $domnode) {
                $this->attr('id', $i + 1);

                echo $domnode->nodeValue;
     });

ProTip:
Any valid callable is accepted, not only closures.

function setattr($chapter, $i, $domnode)
{
    $chapter->attr('id', $i + 1);

    echo $domnode->nodeValue;
}

$book->query('//chapter')
        ->each('setattr');

->map()

maps the current context (after a query or an add/append/prepend operation).

$results = $book->query('//chapter')->map(function($i, $domnode) {
    return $domnode->getAttribute('id');
});

ProTip:
Any valid callable is accepted, not only closures.

function mapNode($ctx, $i, $domnode)
{
    return $domnode->getAttribute('id');
}

$results = $book->query('//chapter')->map('mapNode');

->times($n)

repeats the following method call $n times.

$book->query('//chapters')
        ->times(2)
            ->add('chapter');

If a callable is passed as second argument, the callable is called $n times.

$book->query('//chapters')
        ->times(2, function($i) {
            $this->add('chapter', [ 'id' => $i + 5 ]);
        });

ProTip:
Any valid callable is accepted, not only closures.

function addchapter($chapters, $i)
{
        $chapters->add('chapter', [ 'id' => $i + 5 ]);
}

$book->query('//chapters')
        ->times(2, 'addchapter');

->filter()

filters programmatically the current context (after a query or an add/append/prepend operation).

$book->query('//chapters')
        ->filter(function($i, $node) {
            return $i % 2 === 0;
        })
        ->attr('even');

A false return value informs ->filter() to expunge that particular element from the fluent context.

ProTip:
Any valid callable is accepted, not only closures.

function filtereven($chapter, $i, $node)
{
        return $i % 2 === 0;
}

$book->query('//chapters')
        ->filter('filtereven')
           ->attr('even');

7. Accessing The DOMNode 〉