0
0
PHPprogramming~10 mins

Memory efficiency with generators 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 5.

PHP
<?php
function numbers() {
    for ($i = 1; $i <= 5; $i++) {
        yield [1];
    }
}
?>
Drag options to blanks, or click blank then click option'
A$count
B$j
C$num
D$i
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable not defined in the loop.
Trying to return instead of yield.
2fill in blank
medium

Complete the code to iterate over the generator and print each value.

PHP
<?php
foreach (numbers() as [1]) {
    echo $value . "\n";
}
?>
Drag options to blanks, or click blank then click option'
A$value
B$item
C$num
D$element
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name in the loop body than in the foreach.
Forgetting the $ sign.
3fill in blank
hard

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

PHP
<?php
function squares() {
    for ($i = 1; $i <= 5; $i++) {
        yield [1];
    }
}
?>
Drag options to blanks, or click blank then click option'
A$i * $i
B$i + $i
Cpow($i, 3)
D$i / 2
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or division instead of multiplication.
Using cube instead of square.
4fill in blank
hard

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

PHP
<?php
function evenNumbers() {
    for ($i = 1; $i <= 10; $i++) {
        if ($i [1] 2 == 0) {
            yield [2];
        }
    }
}
?>
Drag options to blanks, or click blank then click option'
A%
B$i
C==
D$num
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong operator for modulus.
Yielding a variable not defined.
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];
        }
    }
}
?>
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 inconsistent variable names.
Yielding only values without keys.