Skip to main content

What is a generator in PHP and why is it memory-efficient?

Senior PHP
Quick Answer A generator is a function using yield instead of return. It produces values one at a time, pausing between each yield. The caller gets an Iterator without the function running to completion. Memory stays flat regardless of how many values - only one value exists at a time. Great for reading large files, paginating DB results, or building pipelines. Much more memory-efficient than returning full arrays.

Answer

Generators return values lazily using yield, reducing memory usage for large datasets.
S
SugharaIQ Editorial Team Verified Answer

This answer has been peer-reviewed by industry experts holding senior engineering roles to ensure technical accuracy and relevance for modern interview standards.

Want to bookmark, take notes, or join discussions?

Sign in to access all features and personalize your learning experience.

Sign In Create Account

Source: SugharaIQ

Ready to level up? Start Practice