Recursive glob() VS. RecursiveDirectoryIterator

The glob() function has been around since PHP4 and it is a very widely used function. Below is an example of a basic recursive glob function as found on php.net.

I did take the liberty of renaming it to “rglob” I felt it was cleaner.

1
2
3
4
5
6
7
8
9
10
11
12
<?php
 
// Does not support flag GLOB_BRACE
function rglob($pattern, $flags = 0) {
    $files = glob($pattern, $flags); 
    foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $files = array_merge($files, rglob($dir.'/'.basename($pattern), $flags));
    }
    return $files;
}
 
?>

While this is fine, you will discover that unless you had this handy function around already, you will end up searching for one, or creating one yourself. This problem was solved in PHP5 but is little known to many PHP developers. The solution: Iterators!

Iterators have become increasingly more popular and more powerful with each new version of PHP5. One of those Iterator objects is the RecursiveDirectoryIterator. Using this class in junction with both the RecursiveIteratorIterator and the RegexIterator brings a powerful combination that allows for faster development.

With a basic understanding of Iterators one can create such a function without some of the research it might take to experiment with glob(). Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
function rsearch($folder, $pattern) {
    $dir = new RecursiveDirectoryIterator($folder);
    $ite = new RecursiveIteratorIterator($dir);
    $files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
    $fileList = array();
    foreach($files as $file) {
        $fileList = array_merge($fileList, $file);
    }
    return $fileList;
}
?>

As you can see, the Iterators will handle everything for you. How nice is that!

You can leave a response, or trackback from your own site.
Subscribe to RSS Feed Subscribe to Tumblr Follow me on Twitter!