1.2.368. Don’t Loop On Yield

Use yield from, instead of looping on a generator <https://www.php.net/`generator>`_ with yield.

yield from delegate the yielding to another generator <https://www.php.net/`generator>`_, and keep calling that generator <https://www.php.net/`generator>`_ until it is finished. It also works with implicit generator <https://www.php.net/`generator>`_ datastructure, like arrays. There is a performance gain when delegating, over looping manually on the generator <https://www.php.net/`generator>`_. You may even consider writing the loop to store all values in an array, then yield from the array.

<?php

function generator() {
    for($i = 0; $i < 10; ++$i) {
        yield $i;
    }
}

function delegatingGenerator() {
    yield from generator();
}

// Too much code here
function generator2() {
    foreach(generator() as $g) {
        yield $g;
    }
}

?>

See also Generator delegation via yield from.

1.2.368.1. Suggestions

  • Use yield from instead of the whole foreach() loop

1.2.368.2. Specs

Short name

Structures/DontLoopOnYield

Rulesets

All, Suggestions

Exakat since

1.5.3

PHP Version

With PHP 7.0 and more recent

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

yield

Examples

Dolibarr, Tikiwiki

Available in

Entreprise Edition, Exakat Cloud