0
0
PHPprogramming~10 mins

Generator function execution model in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a generator function that yields numbers from 1 to 3.

PHP
<?php
function numbers() {
    yield [1];
}

foreach (numbers() as $num) {
    echo $num . " ";
}
?>
Drag options to blanks, or click blank then click option'
A1
B5
C0
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Yielding 0 instead of 1.
Yielding the last number directly without starting from 1.
2fill in blank
medium

Complete the code to yield numbers from 1 to 3 using a loop inside the generator.

PHP
<?php
function numbers() {
    for ($i = 1; $i <= [1]; $i++) {
        yield $i;
    }
}

foreach (numbers() as $num) {
    echo $num . " ";
}
?>
Drag options to blanks, or click blank then click option'
A5
B1
C3
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 5 instead of 3, which yields extra numbers.
Using 0 which yields no numbers.
3fill in blank
hard

Fix the error in the generator function to correctly yield values.

PHP
<?php
function gen() {
    [1] 1;
    [1] 2;
    [1] 3;
}

foreach (gen() as $val) {
    echo $val . " ";
}
?>
Drag options to blanks, or click blank then click option'
Ayield
Breturn
Cecho
Dprint
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of yield.
Using echo or print inside the generator.
4fill in blank
hard

Fill both blanks to create a generator that yields squares of numbers from 1 to 4.

PHP
<?php
function squares() {
    for ($i = 1; $i [1] 4; $i++) {
        yield $i [2] 2;
    }
}

foreach (squares() as $sq) {
    echo $sq . " ";
}
?>
Drag options to blanks, or click blank then click option'
A<=
B**
C*
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using * instead of ** which multiplies but does not square.
Using < which excludes 4.
5fill in blank
hard

Fill all three blanks to create a generator that yields only even numbers from 2 to 6.

PHP
<?php
function evens() {
    for ($n = [1]; $n [2] 6; $n += 2) {
        yield [3];
    }
}

foreach (evens() as $even) {
    echo $even . " ";
}
?>
Drag options to blanks, or click blank then click option'
A1
B<=
C$n
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from 1 which is odd.
Using < which excludes 6.
Yielding a fixed number instead of $n.