📖 Scenario: Imagine you have a list of tasks to do, but you want to handle them one by one without loading all at once. Using yield in PHP helps you do this efficiently.
🎯 Goal: You will create a generator function using yield to produce tasks one at a time, then loop through them to display each task.
📋 What You'll Learn
Create an array called $tasks with exact string values: 'Clean', 'Cook', 'Shop'
Create a generator function called taskGenerator that uses yield to return each task from $tasks
Use a foreach loop with variable $task to iterate over taskGenerator()
Print each task inside the loop using echo
💡 Why This Matters
🌍 Real World
Generators are useful when working with large data sets or streams where loading all data at once is not efficient.
💼 Career
Understanding <code>yield</code> helps in writing memory-efficient PHP code, useful in backend development and data processing jobs.
Progress0 / 4 steps
1
Create the tasks array
Create an array called $tasks with these exact string values: 'Clean', 'Cook', 'Shop'.
PHP
Hint
Use square brackets to create the array and separate values with commas.
2
Create the generator function
Create a generator function called taskGenerator that uses yield to return each task from the $tasks array.
PHP
Hint
Use foreach to loop over $tasks and yield each $task.
3
Loop through the generator
Use a foreach loop with variable $task to iterate over taskGenerator().
PHP
Hint
Use foreach with taskGenerator() and variable $task.
4
Print each task
Inside the foreach loop, print each $task using echo followed by a newline.
PHP
Hint
Use echo $task . "\n"; to print each task on its own line.
Practice
(1/5)
1. What does the yield keyword do in a PHP function?
easy
A. It returns a value and pauses the function, resuming later to produce more values.
B. It immediately stops the function and returns a single value.
C. It creates a new variable inside the function.
D. It converts the function into a class method automatically.
Solution
Step 1: Understand yield behavior
The yield keyword pauses the function and returns a value without ending it.
Step 2: Compare with return
Unlike return, yield allows the function to resume and produce more values later.
Final Answer:
It returns a value and pauses the function, resuming later to produce more values. -> Option A
Quick Check:
Yield pauses and resumes function = A [OK]
Hint: Yield pauses function to produce values one by one [OK]
Common Mistakes:
Confusing yield with return which ends function
Thinking yield creates variables
Assuming yield converts function to class method
2. Which of the following is the correct syntax to yield values from a function in PHP?
easy
A. yield($value);
B. return yield $value;
C. yield => $value;
D. yield $value;
Solution
Step 1: Recall yield syntax
The correct syntax to yield a value is simply yield $value; inside the function.
Step 2: Check other options
Options B, C, and D use invalid or incorrect syntax for yield in PHP.