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.
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."
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 20, 2023 (edit link).