---

Using Iterators in PHP

“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:”

Complete
Story

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends, & analysis