Iterator functions

iterator_apply( $it, ‘callback’, array($it) )

Applies a callback to an objects that implements Iterator:

<?php
function print_caps(Iterator $iterator) {
    echo strtoupper($iterator->current()) . "\n";
    return TRUE;
}

$it = new ArrayIterator(array("Apples", "Bananas", "Cherries"));
iterator_apply($it, "print_caps", array($it));

iterator_count()

counts all the elements in an iterator

iterator_to_array()

converts any iterator to an array (multidimensional if appropriate)

Generator functions

A generator is a function that can be iterated by foreach. It differs from a regular function because it has a yield statement instead of return statement. To understand how to create a generator, first imagine class that returns Fibonacci numbers when its is iterated:

<?php
class GenerateFibonacci implements Iterator {

   private $f1;
   private $f2;
   private $key;

   public function __construct()
   {
      rewind();
   }

   public function rewind()
   {
      $this->key = $this->f0 = 0;
      $this->f1 = 1;
   }

   public function valid()
   {
      return true;// increases without bound.
   }

   public function current()
   {
     return $this->f1 + $this->f0;
   }

   public function next()
   {
      $temp = $this->current;
      $this->f0 = $this->f1;
      $this->f1 = $temp;
      $this->key++;
   }

   public function key()
   {
      return $this->key;
   }
}

$fibonacci = new FibonacciGenerator();

``foreach``($fibonacci => $fib_number) {

  echo $fib_number . ", ";
}

A Fibonacci generator function is much simpler to implement:

<?php
function fibonacci()
{
  $f0 = 0;
  $f1 = 1;

  while ($true) {

    $current = $f1 + $f0;
    $f0 = $f1;
    $f1 = $current;

    yield $current;
}

``foreach``(fibonacci() => $fib_number) {

  echo $fib_number . ", ";
}