Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable not defined in the loop.
Trying to return instead of yield.
✗ Incorrect
The generator yields the current number $i in the loop.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name in the loop body than in the foreach.
Forgetting the $ sign.
✗ Incorrect
The foreach loop variable should match the variable used inside the loop to print.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or division instead of multiplication.
Using cube instead of square.
✗ Incorrect
To yield squares, multiply $i by itself.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong operator for modulus.
Yielding a variable not defined.
✗ Incorrect
Use modulus operator % to check evenness and yield $i.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent variable names.
Yielding only values without keys.
✗ Incorrect
Use $key and $value for keys and values; yield key => value.