0
0
PHPprogramming~10 mins

Why generators are needed in PHP - Test Your Understanding

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

Complete the code to create 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'
A3
B1
C0
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Yielding a number outside the desired range.
Using return instead of yield.
2fill in blank
medium

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

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'
A0
B5
C1
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Setting the loop limit too high or too low.
Using incorrect comparison operators.
3fill in blank
hard

Fix the error in the generator function to yield squares of numbers from 1 to 3.

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

foreach (squares() as $square) {
    echo $square . " ";
}
?>
Drag options to blanks, or click blank then click option'
A*
B+
C**
D//
Attempts:
3 left
💡 Hint
Common Mistakes
Using * instead of ** for exponentiation.
Using addition or integer division operators.
4fill in blank
hard

Fill both blanks to create a generator that yields only even numbers from 1 to 6.

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

foreach (evenNumbers() as $num) {
    echo $num . " ";
}
?>
Drag options to blanks, or click blank then click option'
A6
B%
C==
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect loop limits.
Using wrong operators in the if condition.
5fill in blank
hard

Fill all three blanks to create a generator that yields keys and values from an array where values are greater than 10.

PHP
<?php
function filterArray($arr) {
    foreach ($arr as [1] => [2]) {
        if ([2] > 10) {
            yield [1] => [2];
        }
    }
}

$data = ['a' => 5, 'b' => 15, 'c' => 25];

foreach (filterArray($data) as $key => $value) {
    echo "$key: $value\n";
}
?>
Drag options to blanks, or click blank then click option'
A$key
B$value
C$val
D$k
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in foreach and yield.
Mixing keys and values incorrectly.