RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Using Iterators in PHP

Discover how to use the iterators in the Standard PHP Library


his article shows you how to use the most important iterator classes: ArrayIterator, DirectoryIterator, FilterIterator, and so forth, found in the Standard PHP Library (SPL), and how to integrate SPL with PHP Data Objects (PDO).

The Standard PHP Library

The SPL represents a collection of interfaces and classes for PHP 5 that help resolve some common problems and that let developers take full advantage of object-oriented programming. Some of the SPL's most used capabilities are: advanced array access, the ability to customize collection iteration with foreach or while, enhanced file and directory access, and advanced SimpleXML object handling. But the best new functionality that the SPL provides comes in the form of iterators.

According to Wikipedia, an iterator is an object that allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation. There are several different types of iterators, each discussed in more detail below.

The ArrayIterator Class

This iterator allows you to modify values and keys while iterating over arrays and objects. You can find documentation for the ArrayIterator methods here.

This first example application iterates recursively over a $numbers array, appends a new value at the end of the array, and finally prints it to the screen:

$numbers = array(1 => 'one', 
   2 => 'two', 3 => 'three', 
   4 => 'four', 5 => 'five');
// Create a new ArrayObject instance
$object = new ArrayObject( $numbers );
//Create a new RecursiveIteratorIterator instance and pass it to the 
//RecursiveArrayIterator constructor. 
$iterator = new RecursiveIteratorIterator( new 
echo 'Listing the $numbers array recursively:'.'<br />';
//Iterate over the values in the ArrayObject
foreach ($iterator as $key=>$val)
   echo $key."*****".$val;
echo '<br /><br />';
//Append a value at the end of the array using an object
echo 'Listing the $numbers array recursively after '.
   'appending a new value:'.'<br />';
//Iterate over the values in the ArrayObject
foreach ($iterator as $key=>$val)
   echo $key."*****".$val."\n";
echo '<br />';

The output from the preceding code lists the array twice: once after it is first populated, and again after adding a new value:

Listing the $numbers array recursively:

Listing the $numbers array recursively after appending a new value:
1*****one 2*****two 3*****three 4*****four 5*****five 6*****six

Here's a second example that iterates over a $flowers array using the current(), valid(), and next() methods, as described below:

  • valid(): Checks whether the array contains more entries.
  • next(): Moves to the next entry.
  • current(): Returns the current array entry

Finally, the following example lists the number of elements in the $flowers array using the ArrayObject count() method:

$flowers = array('tulip', 'rose', 
   'lily', 'snowdrop', 'crocus');
//Create a new ArrayObject instance
$arrayObj = new ArrayObject($flowers);
echo ' Sequential list of elements in the $flowers array 
   using getIterator():'.'<br />';
//Iterate over the values in the ArrayObject
for($iterator = $arrayObj->getIterator();
   echo $iterator->key() . ' => ' . 
      $iterator->current() . '<br />';
echo '<br />'.'*******************'.'<br />';
//Counting elements
echo 'The number of elements in the $flowers array is: '.
   $arrayObj->count().'<br />';
//Seeking a given element
$iterator = $arrayObj->getIterator();
echo 'Seeking a given value:'.'<br />';
   echo $iterator->key() . ' => ' . 
      $iterator->current() . '<br />';   

The output is:

Sequential list of elements in the $flowers array using getIterator():
0 => tulip
1 => rose
2 => lily
3 => snowdrop
4 => crocus
The number of elements in the $flowers array is: 5
Seeking a given value:
3 => snowdrop

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date