Complete the code to define a generator function that yields numbers from 1 to 3.
<?php
function numbers() {
yield [1];
}
foreach (numbers() as $num) {
echo $num . " ";
}
?>The generator yields the number 1 first. Using yield 1; starts the sequence.
Complete the code to yield numbers from 1 to 3 using a loop inside the generator.
<?php
function numbers() {
for ($i = 1; $i <= [1]; $i++) {
yield $i;
}
}
foreach (numbers() as $num) {
echo $num . " ";
}
?>The loop should run until 3 to yield numbers 1, 2, and 3.
Fix the error in the generator function to correctly yield values.
<?php
function gen() {
[1] 1;
[1] 2;
[1] 3;
}
foreach (gen() as $val) {
echo $val . " ";
}
?>return instead of yield.echo or print inside the generator.In a generator, yield is used to produce values one at a time.
Fill both blanks to create a generator that yields squares of numbers from 1 to 4.
<?php
function squares() {
for ($i = 1; $i [1] 4; $i++) {
yield $i [2] 2;
}
}
foreach (squares() as $sq) {
echo $sq . " ";
}
?>* instead of ** which multiplies but does not square.< which excludes 4.The loop runs while $i is less than or equal to 4, and squares are calculated using the exponent operator **.
Fill all three blanks to create a generator that yields only even numbers from 2 to 6.
<?php
function evens() {
for ($n = [1]; $n [2] 6; $n += 2) {
yield [3];
}
}
foreach (evens() as $even) {
echo $even . " ";
}
?>< which excludes 6.The loop starts at 2, runs while $n is less than or equal to 6, and yields $n each time.