From the course: Learning the Standard PHP Library

Introducing SPL iterators - PHP Tutorial

From the course: Learning the Standard PHP Library

Start my 1-month free trial

Introducing SPL iterators

- Iterators are arguably one of the most useful aspects of the SPL, but what are they? Iterators are a series of classes that make it easy to traverse a structure, such as an array, an object or an XML file with a foreach loop. For example, DirectoryIterator, FilesystemIterator, and RecursiveDirectoryIterator give you quick access to the file system. You can create selective loops using regular expressions, or callback functions, as filters, and CachingIterator looks ahead for the next element. Internally, all iterators implement the iterator interface, which has five methods. Rewind moves the iterator back to the first element. Key returns the key of the current element, which can either be a number or a string. Current returns the value of the current element. Next moves to the next element, and valid checks whether there's another element to move to. Most of the time, you don't need to access these methods directly. Using the foreach loop calls them automatically, but they're all public methods, so they're available if necessary. Using SPL Iterators offers several advantages. The code is much simpler than replicating the same functionality with a PHP script. Code can often be reused to handle data from different sources. You'll see later in this course how the same code can be used to filter and sort data from XML and JSON. The code runs faster because the underlying classes are written in C, and it often consumes less memory, but perhaps the greatest advantage of all is that iterators can be chained. What this means is that you can pass an iterator as an argument to another, because iterators can be used to filter values. This provides a modular way to traverse a structure extracting only those elements that you're interested in. You'll see an example of how this works in the next video.

Contents