The yield keyword is used in PHP to create a generator function. A generator is a special kind of function that can be paused and resumed during execution, allowing it to produce a sequence of values on-the-fly rather than all at once.


Here's an example that demonstrates the use of yield in PHP:


function myGenerator()
  yield "Hello";
  yield "World";
  yield "!";

foreach (myGenerator() as $value) {
  echo $value . " ";

In the example above, the myGenerator() function is defined as a generator using the yield keyword. The function returns a sequence of values: "Hello", "World", and "!". When the function is called, it does not execute immediately. Instead, it returns a generator object that can be used to iterate over the sequence of values.

The foreach loop then uses the generator object to iterate over the sequence of values returned by myGenerator(). Each time the loop runs, the generator produces the next value in the sequence using the yield keyword.

The output of the code will be: "Hello World !".

Generators can be useful for working with large datasets or performing complex calculations that would otherwise consume a lot of memory or processing power. By generating values on-the-fly instead of all at once, generators can help you write more efficient and scalable PHP code.

Practice Your Knowledge

What is the function of the 'yield' keyword in PHP?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?