From the course: Learning the Standard PHP Library

Using SPL iterators - PHP Tutorial

From the course: Learning the Standard PHP Library

Start my 1-month free trial

Using SPL iterators

- All The SPL iterators are built in classes, so you create an iterator by creating an instance of the class with the new keyword. Many iterators let you set options using class constants. This means the constant is preceded by the class name and the scope resolution operator two colons. For example, this constant sets the option for file system iterator to skip the dot files that represent the current and parent directories. You can set options either at the same time as instantiating the iterator or by using the iterators set flags method. You can chain iterators to fine tune which elements are selected as you traverse the structure. For example, this uses file system iterator to traverse the current directory. By default, this will include every file. To restrict this to jpegs, you can pass the first iterator as an argument to RegexIterator like this. You can restrict the iterator even further by passing it as an argument to LimitIterator The second argument to LimitIterator specifies the offset at which to begin counting from zero. The third argument specifies how many elements to traverse. So, the result of this chain is to select the third and fourth jpegs in the current directory, rather like using a limit clause when retrieving records from a database. You can then use a foreach loop to do something with those two files. Although, using a foreach loop makes it feel as though you're working with an array, you're not. Each element inside the loop is an object. This is particularly important to remember when you're traversing the file system. In the next chapter, you'll see how to work directly on files and access information about them. Usually, there's no need to convert an iterator to an array, but it's easy enough to do so. Just pass the iterator as an argument to the iterator to array function and assign the return value to a variable. So, now you have a general understanding of what SPL iterators are, let's see them at work.

Contents