Complete the code to yield values from the generator.
<?php
function gen1() {
yield 1;
yield 2;
}
function gen2() {
[1] gen1();
yield 3;
}
foreach (gen2() as $value) {
echo $value . " ";
}
?>The yield from keyword delegates yielding to another generator, allowing gen2() to yield all values from gen1() before continuing.
Complete the code to delegate yielding from the inner generator.
<?php
function inner() {
yield 'a';
yield 'b';
}
function outer() {
[1] inner();
yield 'c';
}
foreach (outer() as $char) {
echo $char;
}
?>yield from delegates yielding to the inner() generator, so outer() yields 'a', 'b', then 'c'.
Fix the error in the code to correctly delegate yielding.
<?php
function numbers() {
yield 1;
yield 2;
}
function combined() {
[1] numbers();
yield 3;
}
foreach (combined() as $num) {
echo $num . ' ';
}
?>Using yield from correctly delegates yielding all values from numbers() inside combined().
Fill both blanks to create a generator that yields squares of numbers greater than 3.
<?php
function squares() {
return [1, 2, 3, 4, 5];
}
function filteredSquares() {
foreach (squares() as $num) {
if ($num [1] 3) {
yield $num [2] 2;
}
}
}
foreach (filteredSquares() as $val) {
echo $val . ' ';
}
?>The condition $num > 3 filters numbers greater than 3, and $num ** 2 yields their squares.
Fill both blanks to create a generator that yields uppercase keys and values greater than 10.
<?php
function data() {
return ['a' => 5, 'b' => 15, 'c' => 20];
}
function filteredData() {
foreach (data() as $key => $value) {
if ($value [1] 10) {
yield [2] => $value;
}
}
}
foreach (filteredData() as $k => $v) {
echo "$k:$v ";
}
?>The condition $value > 10 filters values greater than 10. The key is converted to uppercase with strtoupper($key).