HomePHP Page 5 - Main Methods of the DirectoryIterator Class in PHP 5
Resetting a directory’s internal pointer: the rewind() method - PHP
The DirectoryIterator class is an important part of the Standard PHP Library (SPL). Among other things, it lets you traverse any specified directory with a regular "foreach" loop. In this first article of a three-part series, some of the most relevant methods that come with the “DirectoryIterator” class are covered.
I’m pretty sure that you’ve realized the great functionality provided by the “DirectoryIterator” class. Nevertheless, I’d like you to learn an additional method that can be really useful when working specifically with directories.
Since the code samples that I wrote before showed how easy it is to work with directories that can be handled as array elements, this new example demonstrates how to use the handy “rewind()” method, which wraps the overall functionality exposed by the “DirectoryIterator” class. Take a look at the following source code:
$dirProc=new DirectoryIterator('default_path/'); foreach($dirProc as $dirContent){ echo 'Value of current element is as follows : '.$dirContent->current().'<br />'; } // reset directory pointer by 'rewind()' method $dirProc->rewind(); // display first element of directory echo 'First element in directory is the following : '.$dirProc->current();
As the above example illustrates, the “rewind()” method behaves nearly identical to the “reset()” function that you’ve probably used hundreds of times when processing regular arrays. In this case, after iterating over the specified directory, the script resets the internal pointer, and finally displays the first element of that directory. This condition is clearly reflected by the following output:
Value of current element is as follows : . Value of current element is as follows : .. Value of current element is as follows : file1.txt Value of current element is as follows : file2.txt First element in directory is the following : .
All right, I guess that this final example gives you a good idea of how the “DirectoryIterator” class can be used to traverse a particular directory. As homework, I suggest you to tweak all the code samples shown here and introduce your own improvements. Fun is guaranteed!
Wrapping up
That’s all for now. In this first article of the series, I covered some of the most relevant methods that come with the “DirectoryIterator” class, in this way demonstrating how easy is to traverse any specified directory with a regular “foreach” loop.
But this story isn’t over yet. In the next article, I’ll be reviewing other cool methods, which can be very convenient for obtaining information such as size, path, and files contained inside a particular directory. I'll see you in the next part!