Complete the code to yield values from the generator function.
<?php
function numbers() {
yield [1];
}
foreach (numbers() as $num) {
echo $num . " ";
}
?>The yield keyword outputs a value from the generator. Here, yield 1; yields the value 1.
Complete the code to yield keys and values from the generator.
<?php
function letters() {
yield [1] => 'a';
yield 'b';
}
foreach (letters() as $key => $value) {
echo "$key:$value ";
}
?>To yield a key and value, use yield 'key' => 'value';. Here, the key is 'first'.
Fix the error in the generator function to yield numbers 1 to 3.
<?php
function countToThree() {
for ($i = 1; $i <= 3; $i++) {
[1] $i;
}
}
foreach (countToThree() as $num) {
echo $num . " ";
}
?>Inside a generator, use yield to output each value. Using return would end the function immediately.
Fill both blanks to create a generator that yields squares of numbers greater than 2.
<?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 . " ";
}
?>In the generator function, use > to check if $n > 2 and ** to compute the square $n ** 2, then yield it. This yields 9 and 16.
Fill all three blanks to yield keys as uppercase and values as their length for words longer than 3 letters.
<?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 ";
}
?>The condition checks if the word length is greater than 3. The key is the uppercase word, and the value is its length.