In PHP the foreach
-loop is powerful and leads to clean, concise code. But for complex uses, foreach
is harder to use—a generator can address this problem.
With the yield
-statement, a generator function can return multiple times (it pauses its execution). This allows a foreach
-statement to skip over elements, or perform other computations.
We introduce a generator function in the PHP program here called filter_by
. It receives an array and a required starting letter. It filters out elements that do not have the starting letter.
foreach
-loop and specify our generator function (filter_by
) in the first part of the foreach
statement.foreach
-loop.string
element matches the letter argument, we yield that item.foreach
-loop here.function filter_by($source, $letter) { // Step 3: Loop over array elements. foreach ($source as $item) { // Step 4: If first letter of element matches, yield it. if ($item[0] == $letter) { yield $item; } } } // Step 1: create an array. $values = ["bird", "?", "cat", "barn"]; // Step 2: call generator on the array. foreach (filter_by($values, "b") as $item) { // Step 5: Print the items yield ed from the generator. var_dump($item); }string(4) "bird" string(4) "barn"
Generators can move logic from the body of a foreach
-loop into a reusable function. This can clean up PHP programs by reducing duplicated statements.