0
0
PHPprogramming~10 mins

Yield keyword behavior 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 yield values from the generator function.

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

foreach (numbers() as $num) {
    echo $num . " ";
}
?>
Drag options to blanks, or click blank then click option'
A1
Bprint 1
Creturn 1
Decho 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using echo or print instead of yield inside the generator.
Using return instead of yield which ends the function.
2fill in blank
medium

Complete the code to yield keys and values from the generator.

PHP
<?php
function letters() {
    yield [1] => 'a';
    yield 'b';
}

foreach (letters() as $key => $value) {
    echo "$key:$value ";
}
?>
Drag options to blanks, or click blank then click option'
A'first'
B0
C1
D'a'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a number key when a string key is expected.
Omitting the key and only yielding values.
3fill in blank
hard

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

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

foreach (countToThree() as $num) {
    echo $num . " ";
}
?>
Drag options to blanks, or click blank then click option'
Areturn
Bprint
Cecho
Dyield
Attempts:
3 left
💡 Hint
Common Mistakes
Using return inside the loop which stops the generator after first value.
Using echo or print which outputs but does not yield values.
4fill in blank
hard

Fill both blanks to create a generator that yields squares of numbers greater than 2.

PHP
<?php
function squares($numbers) {
    foreach ($numbers as $n) {
        if ($n [1] 2) {
            yield $n[2]2;
        }
    }
}

foreach (squares([1, 2, 3, 4]) 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 < instead of > in the condition.
5fill in blank
hard

Fill all three blanks to yield keys as uppercase and values as their length for words longer than 3 letters.

PHP
<?php
function wordInfo($words) {
    foreach ($words as $word) {
        if (strlen($word) [1] 3) {
            yield [2] => [3];
        }
    }
}

foreach (wordInfo(['apple', 'bat', 'carrot']) as $key => $value) {
    echo "$key:$value ";
}
?>
Drag options to blanks, or click blank then click option'
A>
Bstrlen($word)
C$word
Dstrtoupper($word)
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in the condition.
Yielding the word as key without converting to uppercase.
Yielding the word instead of its length as value.