Skip to content

Instantly share code, notes, and snippets.

@alan-ps
Created August 13, 2019 09:46
Show Gist options
  • Save alan-ps/a95bf38f72b77fa71bbd7851c7a235e7 to your computer and use it in GitHub Desktop.
Save alan-ps/a95bf38f72b77fa71bbd7851c7a235e7 to your computer and use it in GitHub Desktop.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate.

Example
<?php

/**
 * Helper function to get $count of even numbers.
 */
function func($count) {
  for ($i = 0; $i < $count; $i++) {
    yield $i * 2;      
  }
}

foreach (func(100) as $value) {
  echo $value . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment