[{"data":1,"prerenderedAt":741},["ShallowReactive",2],{"post-\u002Fdifference-between-generators-and-iterators-in-php":3},{"page":4,"translation":620,"nav":622,"related":735,"random":736},{"id":5,"title":6,"body":7,"categories":604,"category":606,"date":607,"description":608,"draft":609,"extension":610,"image":611,"kind":606,"lang":612,"meta":613,"navigation":152,"path":614,"readingTime":149,"seo":615,"slug":616,"stem":616,"tags":606,"translationKey":617,"type":605,"updated":618,"__hash__":619},"posts\u002Fdifference-between-generators-and-iterators-in-php.md","The Key Differences Between PHP Generators and Iterators",{"type":8,"value":9,"toc":593},"minimark",[10,14,63,69,93,98,101,106,112,327,331,337,390,397,400,404,410,417,421,515,517,521,549,551,555,576,579,584,589],[11,12,13],"p",{},"PHP generators and PHP iterators are both tools that can be used to create custom iteration mechanisms in PHP. However, there are some key differences between the two.",[15,16,17,24],"blockquote",{},[11,18,19,20],{},"💡 ",[21,22,23],"strong",{},"Quick Summary (TL;DR):",[25,26,27,39,49],"ul",{},[28,29,30,33,34,38],"li",{},[21,31,32],{},"Generators:"," Lightweight, stateful functions that use the ",[35,36,37],"code",{},"yield"," keyword to return values lazily. Extremely memory-efficient.",[28,40,41,44,45,48],{},[21,42,43],{},"Iterators:"," Classes implementing the ",[35,46,47],{},"Iterator"," interface (requiring 5 methods). They offer full control and rewindability but require more boilerplate.",[28,50,51,54,55,58,59,62],{},[21,52,53],{},"Core Choice:"," Use ",[21,56,57],{},"Generators"," for simple, lazy data streams (e.g. reading huge files). Use ",[21,60,61],{},"Iterators"," when you need custom object state management or rewindable loops.",[11,64,65,66,68],{},"First, let's define what each of these terms means. A generator is a special function in PHP that allows the developer to create an iterator that can be used to iterate over a set of values. Generators are created using the ",[35,67,37],{}," keyword, which allows the generator function to pause execution and return a value to the caller. The generator function can then be resumed at a later time, allowing the developer to iterate over the values returned by the generator.",[11,70,71,72,74,75,78,79,78,82,78,85,88,89,92],{},"On the other hand, an iterator is an object that implements the ",[35,73,47],{}," interface in PHP. This interface defines a set of methods that must be implemented in order for an object to be considered an iterator. These methods include ",[35,76,77],{},"rewind",", ",[35,80,81],{},"current",[35,83,84],{},"key",[35,86,87],{},"next",", and ",[35,90,91],{},"valid",", which allow the developer to control the iteration process and access the values being iterated over.",[94,95,97],"h2",{"id":96},"implementation-comparison-code-example","Implementation Comparison: Code Example",[11,99,100],{},"To understand the difference, let's look at how we can implement a custom range generator using both methods.",[102,103,105],"h3",{"id":104},"_1-using-a-custom-iterator-class","1. Using a Custom Iterator Class",[11,107,108,109,111],{},"Implementing the ",[35,110,47],{}," interface requires creating a class and defining five distinct lifecycle methods:",[113,114,119],"pre",{"className":115,"code":116,"language":117,"meta":118,"style":118},"language-php shiki shiki-themes github-light github-dark","class RangeIterator implements Iterator {\n    private int $start;\n    private int $end;\n    private int $current;\n\n    public function __construct(int $start, int $end) {\n        $this->start = $start;\n        $this->end = $end;\n    }\n\n    public function rewind(): void {\n        $this->current = $this->start;\n    }\n\n    public function current(): mixed {\n        return $this->current;\n    }\n\n    public function key(): mixed {\n        return $this->current;\n    }\n\n    public function next(): void {\n        $this->current++;\n    }\n\n    public function valid(): bool {\n        return $this->current \u003C= $this->end;\n    }\n}\n\n\u002F\u002F Usage\n$range = new RangeIterator(1, 1000000);\nforeach ($range as $number) {\n    \u002F\u002F Process $number\n}\n","php","",[35,120,121,129,135,141,147,154,160,166,172,178,183,189,195,200,205,211,217,222,227,233,238,243,248,254,260,265,270,276,282,287,293,298,304,310,316,322],{"__ignoreMap":118},[122,123,126],"span",{"class":124,"line":125},"line",1,[122,127,128],{},"class RangeIterator implements Iterator {\n",[122,130,132],{"class":124,"line":131},2,[122,133,134],{},"    private int $start;\n",[122,136,138],{"class":124,"line":137},3,[122,139,140],{},"    private int $end;\n",[122,142,144],{"class":124,"line":143},4,[122,145,146],{},"    private int $current;\n",[122,148,150],{"class":124,"line":149},5,[122,151,153],{"emptyLinePlaceholder":152},true,"\n",[122,155,157],{"class":124,"line":156},6,[122,158,159],{},"    public function __construct(int $start, int $end) {\n",[122,161,163],{"class":124,"line":162},7,[122,164,165],{},"        $this->start = $start;\n",[122,167,169],{"class":124,"line":168},8,[122,170,171],{},"        $this->end = $end;\n",[122,173,175],{"class":124,"line":174},9,[122,176,177],{},"    }\n",[122,179,181],{"class":124,"line":180},10,[122,182,153],{"emptyLinePlaceholder":152},[122,184,186],{"class":124,"line":185},11,[122,187,188],{},"    public function rewind(): void {\n",[122,190,192],{"class":124,"line":191},12,[122,193,194],{},"        $this->current = $this->start;\n",[122,196,198],{"class":124,"line":197},13,[122,199,177],{},[122,201,203],{"class":124,"line":202},14,[122,204,153],{"emptyLinePlaceholder":152},[122,206,208],{"class":124,"line":207},15,[122,209,210],{},"    public function current(): mixed {\n",[122,212,214],{"class":124,"line":213},16,[122,215,216],{},"        return $this->current;\n",[122,218,220],{"class":124,"line":219},17,[122,221,177],{},[122,223,225],{"class":124,"line":224},18,[122,226,153],{"emptyLinePlaceholder":152},[122,228,230],{"class":124,"line":229},19,[122,231,232],{},"    public function key(): mixed {\n",[122,234,236],{"class":124,"line":235},20,[122,237,216],{},[122,239,241],{"class":124,"line":240},21,[122,242,177],{},[122,244,246],{"class":124,"line":245},22,[122,247,153],{"emptyLinePlaceholder":152},[122,249,251],{"class":124,"line":250},23,[122,252,253],{},"    public function next(): void {\n",[122,255,257],{"class":124,"line":256},24,[122,258,259],{},"        $this->current++;\n",[122,261,263],{"class":124,"line":262},25,[122,264,177],{},[122,266,268],{"class":124,"line":267},26,[122,269,153],{"emptyLinePlaceholder":152},[122,271,273],{"class":124,"line":272},27,[122,274,275],{},"    public function valid(): bool {\n",[122,277,279],{"class":124,"line":278},28,[122,280,281],{},"        return $this->current \u003C= $this->end;\n",[122,283,285],{"class":124,"line":284},29,[122,286,177],{},[122,288,290],{"class":124,"line":289},30,[122,291,292],{},"}\n",[122,294,296],{"class":124,"line":295},31,[122,297,153],{"emptyLinePlaceholder":152},[122,299,301],{"class":124,"line":300},32,[122,302,303],{},"\u002F\u002F Usage\n",[122,305,307],{"class":124,"line":306},33,[122,308,309],{},"$range = new RangeIterator(1, 1000000);\n",[122,311,313],{"class":124,"line":312},34,[122,314,315],{},"foreach ($range as $number) {\n",[122,317,319],{"class":124,"line":318},35,[122,320,321],{},"    \u002F\u002F Process $number\n",[122,323,325],{"class":124,"line":324},36,[122,326,292],{},[102,328,330],{"id":329},"_2-using-a-generator-function","2. Using a Generator Function",[11,332,333,334,336],{},"A generator simplifies this entire process into a single function using the ",[35,335,37],{}," keyword:",[113,338,340],{"className":115,"code":339,"language":117,"meta":118,"style":118},"function rangeGenerator(int $start, int $end) {\n    for ($i = $start; $i \u003C= $end; $i++) {\n        yield $i;\n    }\n}\n\n\u002F\u002F Usage\n$range = rangeGenerator(1, 1000000);\nforeach ($range as $number) {\n    \u002F\u002F Process $number\n}\n",[35,341,342,347,352,357,361,365,369,373,378,382,386],{"__ignoreMap":118},[122,343,344],{"class":124,"line":125},[122,345,346],{},"function rangeGenerator(int $start, int $end) {\n",[122,348,349],{"class":124,"line":131},[122,350,351],{},"    for ($i = $start; $i \u003C= $end; $i++) {\n",[122,353,354],{"class":124,"line":137},[122,355,356],{},"        yield $i;\n",[122,358,359],{"class":124,"line":143},[122,360,177],{},[122,362,363],{"class":124,"line":149},[122,364,292],{},[122,366,367],{"class":124,"line":156},[122,368,153],{"emptyLinePlaceholder":152},[122,370,371],{"class":124,"line":162},[122,372,303],{},[122,374,375],{"class":124,"line":168},[122,376,377],{},"$range = rangeGenerator(1, 1000000);\n",[122,379,380],{"class":124,"line":174},[122,381,315],{},[122,383,384],{"class":124,"line":180},[122,385,321],{},[122,387,388],{"class":124,"line":185},[122,389,292],{},[11,391,392,393,396],{},"Both methods achieve the same result and run in ",[21,394,395],{},"O(1) memory complexity"," (they do not load all 1,000,000 numbers into memory at once). However, the generator version requires significantly less boilerplate code.",[398,399],"hr",{},[94,401,403],{"id":402},"detailed-differences","Detailed Differences",[11,405,406,407,409],{},"One key difference between generators and iterators is the way in which they are implemented. Generators are created using a special function syntax, while iterators are created by implementing the ",[35,408,47],{}," interface in a class. This means that generators are generally easier to implement, since they only require the use of a single function rather than a full class. However, iterators offer more flexibility and control over the iteration process, since they allow the developer to implement the full set of iterator methods.",[11,411,412,413,416],{},"Another difference between generators and iterators is the way in which they are used. Generators are generally easier to use, since they can be iterated over using a ",[35,414,415],{},"foreach"," loop just like any other iterable object. On the other hand, iterators require the use of the iterator methods in order to control the iteration process. This can make iterators more complex to use, but also allows for more fine-grained control over the iteration process.",[102,418,420],{"id":419},"feature-comparison-table","Feature Comparison Table",[422,423,424,439],"table",{},[425,426,427],"thead",{},[428,429,430,435,437],"tr",{},[431,432,434],"th",{"align":433},"left","Feature",[431,436,57],{"align":433},[431,438,61],{"align":433},[440,441,442,460,473,485,502],"tbody",{},[428,443,444,450,455],{},[445,446,447],"td",{"align":433},[21,448,449],{},"Syntax",[445,451,452,453],{"align":433},"Function with ",[35,454,37],{},[445,456,457,458],{"align":433},"Class implementing ",[35,459,47],{},[428,461,462,467,470],{},[445,463,464],{"align":433},[21,465,466],{},"Boilerplate Code",[445,468,469],{"align":433},"Extremely low",[445,471,472],{"align":433},"High (Requires 5 methods)",[428,474,475,480,483],{},[445,476,477],{"align":433},[21,478,479],{},"Memory Footprint",[445,481,482],{"align":433},"Low (O(1) storage overhead)",[445,484,482],{"align":433},[428,486,487,492,495],{},[445,488,489],{"align":433},[21,490,491],{},"Rewindability",[445,493,494],{"align":433},"No (Cannot rewind once closed)",[445,496,497,498,501],{"align":433},"Yes (Supports ",[35,499,500],{},"rewind()",")",[428,503,504,509,512],{},[445,505,506],{"align":433},[21,507,508],{},"State Management",[445,510,511],{"align":433},"Handled automatically by PHP engine",[445,513,514],{"align":433},"Managed manually via class properties",[398,516],{},[94,518,520],{"id":519},"frequently-asked-questions-faq","Frequently Asked Questions (FAQ)",[25,522,523,536],{},[28,524,525,528],{},[21,526,527],{},"Can you rewind a generator in PHP?",[25,529,530],{},[28,531,532,533,535],{},"No, once a generator function finishes yielding or is closed, it cannot be rewound. Attempting to rewind it in a second ",[35,534,415],{}," loop will throw an exception. If you need to iterate again, you must call the generator function to create a new Generator object.",[28,537,538,541],{},[21,539,540],{},"When should I use a custom Iterator class instead of a Generator?",[25,542,543],{},[28,544,545,546,548],{},"You should use a custom ",[35,547,47],{}," class if you need to attach additional domain logic to the iterator object, if the iteration state is highly complex and depends on multiple custom properties, or if the consumer needs to rewind and repeat the iteration multiple times without recreating the data source.",[398,550],{},[94,552,554],{"id":553},"official-documentation-references","Official Documentation & References",[25,556,557,569],{},[28,558,559],{},[560,561,568],"a",{"href":562,"rel":563,"target":567},"https:\u002F\u002Fwww.php.net\u002Fmanual\u002Fen\u002Flanguage.generators.php",[564,565,566],"nofollow","noopener","noreferrer","_blank","PHP Official Manual: Generators",[28,570,571],{},[560,572,575],{"href":573,"rel":574,"target":567},"https:\u002F\u002Fwww.php.net\u002Fmanual\u002Fen\u002Fclass.iterator.php",[564,565,566],"PHP Official Manual: The Iterator Interface",[11,577,578],{},"In conclusion, both generators and iterators are useful tools for creating custom iteration mechanisms in PHP. Generators are easier to implement and use, but offer less control over the iteration process. Iterators offer more flexibility and control, but are more complex to implement and use. The choice between the two will depend on the specific needs of your application.",[580,581,583],"h5",{"id":582},"changes-made-in-this-article","Changes Made in This Article",[25,585,586],{},[28,587,588],{},"20.06.2026: Added TL;DR summary box, side-by-side code implementation examples, comparison table, FAQ section, official manual links, and LLO (AI visibility) optimizations.",[590,591,592],"style",{},"html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}",{"title":118,"searchDepth":131,"depth":131,"links":594},[595,599,602,603],{"id":96,"depth":131,"text":97,"children":596},[597,598],{"id":104,"depth":137,"text":105},{"id":329,"depth":137,"text":330},{"id":402,"depth":131,"text":403,"children":600},[601],{"id":419,"depth":137,"text":420},{"id":519,"depth":131,"text":520},{"id":553,"depth":131,"text":554},[605],"technical",null,"2023-01-11","PHP generators and PHP iterators are both tools that can be used to create custom iteration mechanisms in PHP. However, there are some key differences…",false,"md","\u002Fimages\u002Fhero\u002Fgenerators-vs-iterators.avif","en",{},"\u002Fdifference-between-generators-and-iterators-in-php",{"title":6,"description":608},"difference-between-generators-and-iterators-in-php","php-generators-vs-iterators","2026-06-20","FNIVlreEUTN6UU3m2ae2RgqWw29Hu_YFdc1UB3tqI5U",{"path":621},"\u002Ftr\u002Fphp-generator-ve-iterator-farki",{"prev":623,"next":626,"others":629,"lucky":734,"readingTime":149},{"path":624,"title":625},"\u002Fhow-to-set-up-a-self-hosted-api-gateway-a-comprehensive-guide","How to Set Up a Self-Hosted API Gateway: A Comprehensive Guide",{"path":627,"title":628},"\u002Fphp-and-machine-learning-a-winning-combination-with-php-ml","PHP and Machine Learning: A Winning Combination with PHP-ML",[630,633,636,639,642,645,648,651,654,657,660,663,666,669,672,675,678,681,684,687,690,693,694,695,698,701,704,707,710,713,716,719,722,725,728,731],{"path":631,"title":632},"\u002Ffull-stack-project-development","Sample REST API Project",{"path":634,"title":635},"\u002Frest-api-authentication","How to Perform REST API Authentication?",{"path":637,"title":638},"\u002Frest-api-design","REST API Design: Principles and Output Format",{"path":640,"title":641},"\u002Frest-api-documentation-and-testing","How to Document and Test a REST API?",{"path":643,"title":644},"\u002Frest-api-error-handling","How to Perform REST API Error Handling?",{"path":646,"title":647},"\u002Frest-api-security","How to Secure a REST API?",{"path":649,"title":650},"\u002Frest-api-uri-structure","What Should the REST API URI Structure Be?",{"path":652,"title":653},"\u002Ftroubleshooting-cyberpanel-inaccessibility-after-ubuntu-release-upgrade","Troubleshooting CyberPanel Inaccessibility After Ubuntu Release Upgrade",{"path":655,"title":656},"\u002Freset-wordpress-admin-password-using-wp-cli","Reset WordPress Admin Password Using WP-CLI",{"path":658,"title":659},"\u002Fgraphql-vs-rest-api-which-is-the-best-choice-for-headless-wordpress","GraphQL vs REST API: Which is the Best Choice for Headless WordPress?",{"path":661,"title":662},"\u002Fgrow-your-business-in-turkey-with-expert-wordpress-plugin-and-theme-localization-and-support-services","Grow Your Business in Turkey with Expert WordPress Plugin and Theme Localization and Support Services",{"path":664,"title":665},"\u002Fgetting-started-with-devops-understanding-the-principles-and-adopting-the-tools","Getting Started with DevOps: Understanding the Principles and Adopting the Tools",{"path":667,"title":668},"\u002Fphp-graphql-development-advanced-techniques-for-optimizing-your-apis","PHP GraphQL Development: Advanced Techniques for Optimizing Your APIs",{"path":670,"title":671},"\u002Fadvanced-techniques-for-dependency-injection-in-php-tips-code-samples-and-faqs","Advanced Techniques for Dependency Injection in PHP: Tips, Code Samples, and FAQs",{"path":673,"title":674},"\u002Fmaximize-the-potential-of-headless-wordpress-with-graphql","Maximize the Potential of Headless WordPress with GraphQL",{"path":676,"title":677},"\u002Fwriting-clean-modular-and-reusable-code-in-php","Best Practices for Writing Clean, Modular, and Reusable Code in PHP",{"path":679,"title":680},"\u002Fheadless-cmss-an-overview-of-popular-alternatives-to-contentful-and-wordpress","Headless CMSs: An Overview of Popular Alternatives to Contentful and WordPress",{"path":682,"title":683},"\u002Fci-cd-for-php-a-comprehensive-guide","CI\u002FCD for PHP: A Comprehensive Guide",{"path":685,"title":686},"\u002Fintroduction-to-php-namespaces-a-beginners-guide-to-structuring-your-code","Introduction to PHP Namespaces: A Beginner's Guide to Structuring Your Code",{"path":688,"title":689},"\u002Fwhat-is-graylog-a-powerful-tool-for-collecting-indexing-and-analyzing-log-data","What is Graylog? A Powerful Tool for Collecting, Indexing, and Analyzing Log Data",{"path":691,"title":692},"\u002Felevate-your-turkish-audience-experience-with-professional-wordpress-plugin-and-theme-translation","Elevate Your Turkish Audience Experience with Professional WordPress Plugin and Theme Translation",{"path":624,"title":625},{"path":627,"title":628},{"path":696,"title":697},"\u002Fphp-generators-a-beginners-guide-to-iteration","PHP Generators: A Beginner's Guide to Iteration",{"path":699,"title":700},"\u002Fmastering-closures-in-javascript-a-beginners-guide","Mastering Closures in JavaScript: A Beginner's Guide",{"path":702,"title":703},"\u002Fthe-top-php-certification-programs-for-developers","The Top PHP Certification Programs for Developers",{"path":705,"title":706},"\u002Fhow-to-revalidate-next-js-isr-cache-on-demand-cache-regeneration","How to Revalidate Next.js ISR Cache? On-Demand Cache Regeneration",{"path":708,"title":709},"\u002Ftips-for-translating-a-wordpress-plugin-wordpress-theme-to-turkish","Tips for Translating a WordPress Plugin \u002F WordPress Theme to Turkish",{"path":711,"title":712},"\u002Fall-about-headless-wordpress","All About Headless WordPress",{"path":714,"title":715},"\u002Finstall-composer-on-ubuntu","How to Install Composer on Ubuntu \u002F Linux",{"path":717,"title":718},"\u002Fwhat-is-an-api-gateway","What is an API Gateway? Should You Use It?",{"path":720,"title":721},"\u002Fis-jwt-safe-or-is-it-vulnerable","Is JWT Safe or Is It Vulnerable?",{"path":723,"title":724},"\u002Ftailwind-css-to-use-or-not-to-use-that-is-the-question","Tailwind CSS! To use? Or not to use? That is the question.",{"path":726,"title":727},"\u002Fwhat-is-hateoas","What is HATEOAS?",{"path":729,"title":730},"\u002Fhello-world","Hello World: A New Multilingual Journey",{"path":732,"title":733},"\u002Fwhat-is-ecmascript","What is ECMAScript? What is not?",{"path":661,"title":662},[],[737,739,740],{"path":720,"title":721,"date":738},"2022-05-12",{"path":646,"title":647,"date":618},{"path":726,"title":727,"date":738},1782141981270]