Complete the code to create a generator function that yields numbers from 1 to 3.
<?php
function numbers() {
yield [1];
}
foreach (numbers() as $num) {
echo $num . " ";
}
?>The yield keyword outputs values one at a time. Here, yielding 1 starts the sequence.
Complete the code to yield numbers from 1 to 3 inside a loop.
<?php
function numbers() {
for ($i = 1; $i <= [1]; $i++) {
yield $i;
}
}
foreach (numbers() as $num) {
echo $num . " ";
}
?>The loop runs while $i is less than or equal to 3, yielding numbers 1, 2, and 3.
Fix the error in the generator function to yield squares of numbers from 1 to 3.
<?php
function squares() {
for ($i = 1; $i <= 3; $i++) {
yield $i [1] 2;
}
}
foreach (squares() as $square) {
echo $square . " ";
}
?>* instead of ** for exponentiation.In PHP 7+, ** is the exponentiation operator, used here to square the number.
Fill both blanks to create a generator that yields only even numbers from 1 to 6.
<?php
function evenNumbers() {
for ($i = 1; $i <= [1]; $i++) {
if ($i [2] 2 == 0) {
yield $i;
}
}
}
foreach (evenNumbers() as $num) {
echo $num . " ";
}
?>The loop runs up to 6, and the modulus operator % checks if the number is even.
Fill all three blanks to create a generator that yields keys and values from an array where values are greater than 10.
<?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";
}
?>The foreach loop uses $key and $value to iterate and yield key-value pairs where the value is greater than 10.