Understanding Generators in PHP

What is PHP Generators ?

As per the php wiki “A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.”

so what that means?
In general,  generators  functions allow you to declare a function that behaves like an iterator by yielding value and saving its state so that when its called again; iteration can continue. This is very helpful to save memory  when iterating large data set.


Lets take a example of simple range iteration:

function my_range($start,$end)  {
    $out = [];
    for($i=$start; $i<=$end; $i++) {
        $out[] = $i;
    return $out;

foreach( y_range(0,1000) as $j) {
//logic here

 In this example, my_range() function will store every output in array, since the array is big we need more memory to store. So if the range set is too high, most probably we will run out of memory. 

Lets do same thing  with Generators:

function my_range($start,$end)  {
       for($i=$start; $i<=$end; $i++) {
           yield $i;

foreach( y_range(0,1000) as $j) {
//logic here

In above example, each time foreach is run only one value is return, and state (instance) is saved in “yield” so next time it will call next() and continue. This way each time we just need integer memory space each time that will save lots of memory and also results in performance.

Apart from getting value we can also pass value to generators


function my_range($start,$end)  {
       for($i=$start; $i<=$end; $i++) {
       $command = (yield $i); 
       if($command =='terminate')
$iterator = y_range(0,1000);
foreach($iterator as $j) { //logic here
    if(//condition) {


send function is use to send command back to generator.

Additional functions:

Since generators implements iterator interface class we can use additional functions:

current ( void )
 scalar key ( void )
 void next ( void )
 void rewind ( void )
 boolean valid

Whats new in PHP 5.5 / 5.4 / 5.3?

Whats new in PHP?

This is a quick reference on whats been added / removed or upgraded on new versions of php.

PHP 5.5

Release date: 2013-06-20

Features and Updates

  1. Generators and coroutines
  2. “finally” keyword
  3. New password hashing API
  4. “foreach” now supports list()
  5. “empty()” supports arbitrary expressions
  6. Array and string literal dereferencing
  7. Zend OPcache extension for opcode caching.
  8. Array_column
  9. Improvements to GD
  10. Class name resolution via::class
  11. Datetime impromvents
  12. A lot more improvements and fixes.

PHP 5.4

Release date: 2012-03-01

Features and Updates

  1. Trait support
  2. Short array syntax support
  3. Built-in web server (CLI).
  4. Performance and reduced memory requirements
  5. Instance Method Call
  6. Closure Binding
  7. Objects as Functions ( Function de-refernecing)
  8. JsonSerializable Interface
  9. Binary Notation
  10. Short open tag
  11. Session Upload progress
  12. Default charset is now UTF-8

Many more improvement and fixes

Removed items:

  • register_globals,
  • safe_mode,
  • allow_call_time_pass_reference,
  • session_register(),
  • session_unregister()
  • and session_is_registered().
  • break / continue $var syntax removed
  • ext/sqlite moved to pecl

PHP 5.3

release date: 2009-06-30

Features and Updates

  1. Namespaces concept is added in Php 5.3
  2. Support for Late Static Bindings has been added.
  3. Support for jump labels (limited goto) has been added.
  4. There are two new magic methods, __callStatic() and __invoke().
  5. Nowdoc syntax is now supported, similar to Heredoc syntax, but with single quotes.
  6. Constants can now be declared outside a class using the const keyword.
  7. Ternary short cut “?:”
  8. Optional garbage collection for cyclic references
  9. Optional mysqlnd PHP native replacement for libmysql
  10. 140+ bug fixes.

Removed items:

Removed the following extensions: ext/mhash (see ext/hash), ext/msql, ext/pspell (see ext/enchant), ext/sybase (see ext/sybase_ct)

Moved the following extensions to PECL: ext/ming, ext/fbsql, ext/ncurses, ext/fdf
Removed zend.ze1_compatibility_mode