PHP's Iterator class

1.2k Views Asked by At

I am working with PHP's SPL Recursive Iterators, they are rather confusing to me though but I am learning.

I am using them in a project where I need to recursively grab all files and exclude folders from my result. I was initially using this method...

$directory = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($directory,
                RecursiveIteratorIterator::CHILD_FIRST);

foreach ($iterator as $fileinfo) {    
    if ($fileinfo->isDir()) {
        //skip directories
        //continue;
    }else{
        // process files
    }
}

But then a SO user suggested that I use this method instead so that I would not need to use the isDir() method in my loop...

$directory = new RecursiveDirectoryIterator($path,
                        RecursiveDirectoryIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($directory,
                        RecursiveIteratorIterator::LEAVES_ONLY);

Notice that I used RecursiveDirectoryIterator::SKIP_DOTS in the RecursiveDirectoryIterator constructor which is supposed to skip folders or . and ..

Now I am confused because after some test, even without using the RecursiveDirectoryIterator::SKIP_DOTS it seems to not show them, I am using Windows could that be the reason, do the dots only show up on a Unix type system? Or am I confused to the point that I am missing something?

Also by using RecursiveIteratorIterator::LEAVES_ONLY instead of RecursiveIteratorIterator::CHILD_FIRST it will stop folders from showing up in my result which is what I want but I don't understand why? The documentation has no information on this

1

There are 1 best solutions below

5
On BEST ANSWER

A leaf is an item in the tree which does not have any further items hanging off of it, i.e. it's the end of a branch. By definition, files fit this description.

-- folder
   |
   |- folder
   |  |
   |  |- file       <- a leaf
   |  |
   |  -- folder
   |     |
   |     -- file    <- another leaf
   |
   -- file          <- yet another leaf

By setting the RecursiveIteratorIterator to "leaf only" mode, it's going to skip over any item that's not a leaf.