0
0
PHPprogramming~15 mins

Yield keyword behavior in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Yield keyword behavior
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use echo $task . "\n"; to print each task on its own line.