0
0
PHPprogramming~30 mins

Memory efficiency with generators in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Memory Efficiency with Generators in PHP
📖 Scenario: Imagine you have a large list of numbers and you want to process them one by one without using too much memory. Using generators in PHP helps you do this efficiently.
🎯 Goal: You will create a generator function to yield numbers from 1 to 1000000, then use it to sum these numbers without loading all of them into memory at once.
📋 What You'll Learn
Create a generator function called numberGenerator that yields numbers from 1 to 1000000
Create a variable called total and set it to 0
Use a foreach loop with variable $number to iterate over numberGenerator() and add each number to total
Print the value of total
💡 Why This Matters
🌍 Real World
Generators are useful when working with large data sets like logs, big files, or streams where loading everything at once is not possible.
💼 Career
Understanding generators helps you write efficient code in PHP, which is valuable for backend development and handling large-scale applications.
Progress0 / 4 steps
1
Create the generator function
Create a generator function called numberGenerator that yields numbers from 1 to 1000000 using a for loop.
PHP
Need a hint?

Use yield inside the for loop to return one number at a time.

2
Create the total variable
Create a variable called total and set it to 0.
PHP
Need a hint?

Just write $total = 0; to start counting from zero.

3
Sum numbers using the generator
Use a foreach loop with variable $number to iterate over numberGenerator() and add each number to total.
PHP
Need a hint?

Use foreach (numberGenerator() as $number) and inside add $number to $total.

4
Print the total sum
Write print($total); to display the sum of numbers from 1 to 1000000.
PHP
Need a hint?

The sum of numbers from 1 to 1000000 is 500000500000. Use print($total); to show it.