[{"data":1,"prerenderedAt":571},["ShallowReactive",2],{"post-\u002Fphp-generators-a-beginners-guide-to-iteration":3},{"page":4,"translation":428,"nav":442,"related":555,"random":564},{"id":5,"title":6,"body":7,"categories":426,"category":428,"date":429,"description":430,"draft":431,"extension":432,"image":433,"kind":428,"lang":434,"meta":435,"navigation":301,"path":436,"readingTime":193,"seo":437,"slug":438,"stem":438,"tags":439,"translationKey":428,"type":427,"updated":440,"__hash__":441},"posts\u002Fphp-generators-a-beginners-guide-to-iteration.md","PHP Generators: A Beginner's Guide to Iteration",{"type":8,"value":9,"toc":420},"minimark",[10,56,59,65,68,73,158,160,165,168,209,216,235,238,240,244,247,250,309,312,361,363,367,370,413,416],[11,12,13,21],"blockquote",{},[14,15,16,17],"p",{},"💡 ",[18,19,20],"strong",{},"TL;DR:",[22,23,24,36,46],"ul",{},[25,26,27,30,31,35],"li",{},[18,28,29],{},"What:"," PHP Generators provide a simple, memory-efficient way to implement iterators without the overhead of implementing the ",[32,33,34],"code",{},"Iterator"," interface or loading entire datasets into memory.",[25,37,38,41,42,45],{},[18,39,40],{},"How:"," They use the ",[32,43,44],{},"yield"," keyword to pause execution and return values one-by-one, resuming only when the caller requests the next value.",[25,47,48,51,52,55],{},[18,49,50],{},"Use Case:"," Best suited for processing large log files, database cursors, or generating infinite sequences where traditional arrays would cause ",[32,53,54],{},"Memory Limit Exceeded"," errors.",[14,57,58],{},"PHP generators are a powerful and useful tool in the PHP language. They allow developers to create iterators that can be used to iterate over large datasets without having to load the entire dataset into memory at once. This can be especially useful when working with large datasets or when memory constraints are a concern.",[14,60,61,62,64],{},"Generators are created using the ",[32,63,44],{}," keyword, which allows a 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.",[66,67],"hr",{},[69,70,72],"h3",{"id":71},"traditional-arrays-vs-php-generators","Traditional Arrays vs. PHP Generators",[74,75,76,96],"table",{},[77,78,79],"thead",{},[80,81,82,87,90],"tr",{},[83,84,86],"th",{"align":85},"left","Feature",[83,88,89],{"align":85},"Traditional Array \u002F Iterator",[83,91,92,93,95],{"align":85},"PHP Generator (",[32,94,44],{},")",[97,98,99,113,126,145],"tbody",{},[80,100,101,107,110],{},[102,103,104],"td",{"align":85},[18,105,106],{},"Memory Usage",[102,108,109],{"align":85},"High (stores all elements in memory at once).",[102,111,112],{"align":85},"Extremely Low (only stores current state and value).",[80,114,115,120,123],{},[102,116,117],{"align":85},[18,118,119],{},"Performance",[102,121,122],{"align":85},"Fast for small datasets; can cause OOM crashes for large datasets.",[102,124,125],{"align":85},"Efficient; executes lazily as values are consumed.",[80,127,128,133,139],{},[102,129,130],{"align":85},[18,131,132],{},"Implementation",[102,134,135,136,138],{"align":85},"Easy for arrays; complex for full ",[32,137,34],{}," classes.",[102,140,141,142,144],{"align":85},"Very simple (just a function with ",[32,143,44],{},").",[80,146,147,152,155],{},[102,148,149],{"align":85},[18,150,151],{},"State Retention",[102,153,154],{"align":85},"Yes, you can traverse back and forth.",[102,156,157],{"align":85},"Forward-only traversal (one-pass iteration).",[66,159],{},[161,162,164],"h2",{"id":163},"_1-a-simple-generator-example","1. A Simple Generator Example",[14,166,167],{},"Here is an example of a simple generator function that yields the numbers from 1 to 10:",[169,170,175],"pre",{"className":171,"code":172,"language":173,"meta":174,"style":174},"language-php shiki shiki-themes github-light github-dark","function numberGenerator() {\n    for ($i = 1; $i \u003C= 10; $i++) {\n        yield $i;\n    }\n}\n","php","",[32,176,177,185,191,197,203],{"__ignoreMap":174},[178,179,182],"span",{"class":180,"line":181},"line",1,[178,183,184],{},"function numberGenerator() {\n",[178,186,188],{"class":180,"line":187},2,[178,189,190],{},"    for ($i = 1; $i \u003C= 10; $i++) {\n",[178,192,194],{"class":180,"line":193},3,[178,195,196],{},"        yield $i;\n",[178,198,200],{"class":180,"line":199},4,[178,201,202],{},"    }\n",[178,204,206],{"class":180,"line":205},5,[178,207,208],{},"}\n",[14,210,211,212,215],{},"To use this generator, we can simply iterate over it using a ",[32,213,214],{},"foreach"," loop:",[169,217,219],{"className":171,"code":218,"language":173,"meta":174,"style":174},"foreach (numberGenerator() as $number) {\n    echo $number;\n}\n",[32,220,221,226,231],{"__ignoreMap":174},[178,222,223],{"class":180,"line":181},[178,224,225],{},"foreach (numberGenerator() as $number) {\n",[178,227,228],{"class":180,"line":187},[178,229,230],{},"    echo $number;\n",[178,232,233],{"class":180,"line":193},[178,234,208],{},[14,236,237],{},"This will output the numbers 1 through 10.",[66,239],{},[161,241,243],{"id":242},"_2-memory-comparison-arrays-vs-generators","2. Memory Comparison: Arrays vs. Generators",[14,245,246],{},"To understand why generators are so valuable, let's compare them to the traditional way of generating a range of numbers.",[14,248,249],{},"If we want to generate a range of one million integers, storing them in a traditional array will quickly consume megabytes of memory:",[169,251,253],{"className":171,"code":252,"language":173,"meta":174,"style":174},"\u002F\u002F Traditional approach: loads all elements into memory\nfunction getRange($limit) {\n    $result = [];\n    for ($i = 1; $i \u003C= $limit; $i++) {\n        $result[] = $i;\n    }\n    return $result;\n}\n\n$numbers = getRange(1000000); \u002F\u002F Consumes ~30-40MB of memory\n",[32,254,255,260,265,270,275,280,285,291,296,303],{"__ignoreMap":174},[178,256,257],{"class":180,"line":181},[178,258,259],{},"\u002F\u002F Traditional approach: loads all elements into memory\n",[178,261,262],{"class":180,"line":187},[178,263,264],{},"function getRange($limit) {\n",[178,266,267],{"class":180,"line":193},[178,268,269],{},"    $result = [];\n",[178,271,272],{"class":180,"line":199},[178,273,274],{},"    for ($i = 1; $i \u003C= $limit; $i++) {\n",[178,276,277],{"class":180,"line":205},[178,278,279],{},"        $result[] = $i;\n",[178,281,283],{"class":180,"line":282},6,[178,284,202],{},[178,286,288],{"class":180,"line":287},7,[178,289,290],{},"    return $result;\n",[178,292,294],{"class":180,"line":293},8,[178,295,208],{},[178,297,299],{"class":180,"line":298},9,[178,300,302],{"emptyLinePlaceholder":301},true,"\n",[178,304,306],{"class":180,"line":305},10,[178,307,308],{},"$numbers = getRange(1000000); \u002F\u002F Consumes ~30-40MB of memory\n",[14,310,311],{},"Using a generator, the memory consumption remains virtually constant (a few kilobytes), regardless of the size of the dataset, because it only generates the next value on demand:",[169,313,315],{"className":171,"code":314,"language":173,"meta":174,"style":174},"\u002F\u002F Generator approach: yields values one by one\nfunction getRangeGenerator($limit) {\n    for ($i = 1; $i \u003C= $limit; $i++) {\n        yield $i;\n    }\n}\n\nforeach (getRangeGenerator(1000000) as $number) {\n    \u002F\u002F Consumes \u003C 1KB of memory because it only keeps the current number\n}\n",[32,316,317,322,327,331,335,339,343,347,352,357],{"__ignoreMap":174},[178,318,319],{"class":180,"line":181},[178,320,321],{},"\u002F\u002F Generator approach: yields values one by one\n",[178,323,324],{"class":180,"line":187},[178,325,326],{},"function getRangeGenerator($limit) {\n",[178,328,329],{"class":180,"line":193},[178,330,274],{},[178,332,333],{"class":180,"line":199},[178,334,196],{},[178,336,337],{"class":180,"line":205},[178,338,202],{},[178,340,341],{"class":180,"line":282},[178,342,208],{},[178,344,345],{"class":180,"line":287},[178,346,302],{"emptyLinePlaceholder":301},[178,348,349],{"class":180,"line":293},[178,350,351],{},"foreach (getRangeGenerator(1000000) as $number) {\n",[178,353,354],{"class":180,"line":298},[178,355,356],{},"    \u002F\u002F Consumes \u003C 1KB of memory because it only keeps the current number\n",[178,358,359],{"class":180,"line":305},[178,360,208],{},[66,362],{},[161,364,366],{"id":365},"_3-creating-infinite-sequences","3. Creating Infinite Sequences",[14,368,369],{},"Generators can also be used to create infinite sequences, such as an endless stream of random numbers or an infinite Fibonacci sequence. To do this, the generator function simply needs to run indefinitely and yield values as needed:",[169,371,373],{"className":171,"code":372,"language":173,"meta":174,"style":174},"function fibonacci() {\n    $a = 0;\n    $b = 1;\n    while (true) {\n        yield $a;\n        [$a, $b] = [$b, $a + $b];\n    }\n}\n",[32,374,375,380,385,390,395,400,405,409],{"__ignoreMap":174},[178,376,377],{"class":180,"line":181},[178,378,379],{},"function fibonacci() {\n",[178,381,382],{"class":180,"line":187},[178,383,384],{},"    $a = 0;\n",[178,386,387],{"class":180,"line":193},[178,388,389],{},"    $b = 1;\n",[178,391,392],{"class":180,"line":199},[178,393,394],{},"    while (true) {\n",[178,396,397],{"class":180,"line":205},[178,398,399],{},"        yield $a;\n",[178,401,402],{"class":180,"line":282},[178,403,404],{},"        [$a, $b] = [$b, $a + $b];\n",[178,406,407],{"class":180,"line":287},[178,408,202],{},[178,410,411],{"class":180,"line":293},[178,412,208],{},[14,414,415],{},"Overall, PHP generators are a valuable tool for any PHP developer to have in their toolkit. They allow for efficient iteration over large datasets and can be used to create a wide variety of sequences and iterators.",[417,418,419],"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":174,"searchDepth":187,"depth":187,"links":421},[422,423,424,425],{"id":71,"depth":193,"text":72},{"id":163,"depth":187,"text":164},{"id":242,"depth":187,"text":243},{"id":365,"depth":187,"text":366},[427],"technical",null,"2023-01-10","Learn how PHP generators and the yield keyword can help you iterate over large datasets efficiently without running out of memory.",false,"md","\u002Fimages\u002Fhero\u002Fphp-generators.avif","en",{},"\u002Fphp-generators-a-beginners-guide-to-iteration",{"title":6,"description":430},"php-generators-a-beginners-guide-to-iteration",[173],"2026-06-21","QXHmv9NLV06cVsNr-nP_vMTJzH-XDtxnX5wrzleuTF8",{"prev":443,"next":446,"others":449,"lucky":554,"readingTime":193},{"path":444,"title":445},"\u002Fphp-and-machine-learning-a-winning-combination-with-php-ml","PHP and Machine Learning: A Winning Combination with PHP-ML",{"path":447,"title":448},"\u002Fmastering-closures-in-javascript-a-beginners-guide","Mastering Closures in JavaScript: A Beginner's Guide",[450,453,456,459,462,465,468,471,474,477,480,483,486,489,492,495,498,501,504,507,510,513,516,519,520,521,524,527,530,533,536,539,542,545,548,551],{"path":451,"title":452},"\u002Ffull-stack-project-development","Sample REST API Project",{"path":454,"title":455},"\u002Frest-api-authentication","How to Perform REST API Authentication?",{"path":457,"title":458},"\u002Frest-api-design","REST API Design: Principles and Output Format",{"path":460,"title":461},"\u002Frest-api-documentation-and-testing","How to Document and Test a REST API?",{"path":463,"title":464},"\u002Frest-api-error-handling","How to Perform REST API Error Handling?",{"path":466,"title":467},"\u002Frest-api-security","How to Secure a REST API?",{"path":469,"title":470},"\u002Frest-api-uri-structure","What Should the REST API URI Structure Be?",{"path":472,"title":473},"\u002Ftroubleshooting-cyberpanel-inaccessibility-after-ubuntu-release-upgrade","Troubleshooting CyberPanel Inaccessibility After Ubuntu Release Upgrade",{"path":475,"title":476},"\u002Freset-wordpress-admin-password-using-wp-cli","Reset WordPress Admin Password Using WP-CLI",{"path":478,"title":479},"\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":481,"title":482},"\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":484,"title":485},"\u002Fgetting-started-with-devops-understanding-the-principles-and-adopting-the-tools","Getting Started with DevOps: Understanding the Principles and Adopting the Tools",{"path":487,"title":488},"\u002Fphp-graphql-development-advanced-techniques-for-optimizing-your-apis","PHP GraphQL Development: Advanced Techniques for Optimizing Your APIs",{"path":490,"title":491},"\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":493,"title":494},"\u002Fmaximize-the-potential-of-headless-wordpress-with-graphql","Maximize the Potential of Headless WordPress with GraphQL",{"path":496,"title":497},"\u002Fwriting-clean-modular-and-reusable-code-in-php","Best Practices for Writing Clean, Modular, and Reusable Code in PHP",{"path":499,"title":500},"\u002Fheadless-cmss-an-overview-of-popular-alternatives-to-contentful-and-wordpress","Headless CMSs: An Overview of Popular Alternatives to Contentful and WordPress",{"path":502,"title":503},"\u002Fci-cd-for-php-a-comprehensive-guide","CI\u002FCD for PHP: A Comprehensive Guide",{"path":505,"title":506},"\u002Fintroduction-to-php-namespaces-a-beginners-guide-to-structuring-your-code","Introduction to PHP Namespaces: A Beginner's Guide to Structuring Your Code",{"path":508,"title":509},"\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":511,"title":512},"\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":514,"title":515},"\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":517,"title":518},"\u002Fdifference-between-generators-and-iterators-in-php","The Key Differences Between PHP Generators and Iterators",{"path":444,"title":445},{"path":447,"title":448},{"path":522,"title":523},"\u002Fthe-top-php-certification-programs-for-developers","The Top PHP Certification Programs for Developers",{"path":525,"title":526},"\u002Fhow-to-revalidate-next-js-isr-cache-on-demand-cache-regeneration","How to Revalidate Next.js ISR Cache? On-Demand Cache Regeneration",{"path":528,"title":529},"\u002Ftips-for-translating-a-wordpress-plugin-wordpress-theme-to-turkish","Tips for Translating a WordPress Plugin \u002F WordPress Theme to Turkish",{"path":531,"title":532},"\u002Fall-about-headless-wordpress","All About Headless WordPress",{"path":534,"title":535},"\u002Finstall-composer-on-ubuntu","How to Install Composer on Ubuntu \u002F Linux",{"path":537,"title":538},"\u002Fwhat-is-an-api-gateway","What is an API Gateway? Should You Use It?",{"path":540,"title":541},"\u002Fis-jwt-safe-or-is-it-vulnerable","Is JWT Safe or Is It Vulnerable?",{"path":543,"title":544},"\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":546,"title":547},"\u002Fwhat-is-hateoas","What is HATEOAS?",{"path":549,"title":550},"\u002Fhello-world","Hello World: A New Multilingual Journey",{"path":552,"title":553},"\u002Fwhat-is-ecmascript","What is ECMAScript? What is not?",{"path":499,"title":500},[556,558,560,562],{"path":451,"title":452,"date":557},"2026-06-20",{"path":487,"title":488,"date":559},"2023-01-19",{"path":496,"title":497,"date":561},"2023-01-17",{"path":505,"title":506,"date":563},"2023-01-13",[565,567,569],{"path":517,"title":518,"date":566},"2023-01-11",{"path":525,"title":526,"date":568},"2022-11-10",{"path":502,"title":503,"date":570},"2023-01-15",1782141981453]