Home
Map
Generator Example (yield)Implement a generator and call it in a foreach loop. Filter elements with yield statements.
PHP
This page was last reviewed on May 20, 2023.
Generator. 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.
foreach
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.
Step 1 We create an array of 4 strings. Please note that only 2 of the strings starts with the letter "b."
array
Step 2 We use a foreach-loop and specify our generator function (filter_by) in the first part of the foreach statement.
Step 3 In the generator function, we loop over the array argument (source) with a foreach-loop.
Step 4 If the first character of the string element matches the letter argument, we yield that item.
if
Step 5 We print out the strings that start with the letter "b" inside the 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 20, 2023 (edit link).
Home
Changes
© 2007-2024 Sam Allen.