yield. What will it output when run?<?php function gen() { yield 1; yield 2; yield 3; } foreach (gen() as $value) { echo $value . ' '; } ?>
yield produces values one by one, and the foreach loop prints each.The generator function gen() yields values 1, 2, and 3 sequentially. The foreach loop prints each value followed by a space, resulting in 1 2 3 .
<?php function gen() { yield 'a' => 1; yield 'b' => 2; } foreach (gen() as $key => $value) { echo "$key:$value "; } ?>
The generator yields keys 'a' and 'b' with values 1 and 2 respectively. The foreach loop prints each key and value pair separated by a colon and space.
<?php function gen1() { yield 1; yield 2; } function gen2() { yield from gen1(); yield 3; } foreach (gen2() as $v) { echo $v . ' '; } ?>
yield from keyword delegates yielding to another generator.The gen2() function uses yield from gen1() to yield all values from gen1() first, then yields 3. The output is 1 2 3 .
<?php function gen() { yield 1; } $gen = gen(); $gen->send(10); ?>
The send() method requires the generator to be started (at least one yield executed). Calling send() before starting causes a fatal error.
<?php function gen() { for ($i = 0; $i < 3; $i++) { if ($i === 1) { yield $i; continue; } yield $i * 2; } } $values = iterator_to_array(gen()); echo count($values); ?>
yield is called in the loop.The loop runs 3 times (0,1,2). For i=0 and i=2, it yields i*2. For i=1, it yields i. So total yields: 3.
