0
0
PHPprogramming~15 mins

Generator function execution model in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Generator function execution model
📖 Scenario: Imagine you want to process a list of numbers one by one without loading them all into memory at once. PHP generators help you do this efficiently.
🎯 Goal: You will create a generator function that yields numbers from 1 to 5, then use it to print each number step-by-step.
📋 What You'll Learn
Create a generator function named numberGenerator that yields numbers 1 through 5
Create a variable $gen that holds the generator returned by numberGenerator()
Use a foreach loop with variable $num to iterate over $gen
Print each number inside the loop using echo
💡 Why This Matters
🌍 Real World
Generators are useful when working with large data streams or files where loading everything at once is not efficient.
💼 Career
Understanding generators helps in writing memory-efficient PHP code, important for backend development and data processing tasks.
Progress0 / 4 steps
1
Create the generator function
Write a generator function called numberGenerator that yields the numbers 1, 2, 3, 4, and 5 one by one using yield.
PHP
Need a hint?

Use the yield keyword inside the function to return each number one at a time.

2
Create the generator variable
Create a variable called $gen and assign it the generator returned by calling numberGenerator().
PHP
Need a hint?

Call the function numberGenerator() and assign it to $gen.

3
Iterate over the generator
Use a foreach loop with variable $num to iterate over $gen.
PHP
Need a hint?

Use foreach ($gen as $num) to get each number from the generator.

4
Print each number
Inside the foreach loop, print each number stored in $num followed by a newline using echo.
PHP
Need a hint?

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