0

How to get a list of first children directory names inside a directory?

Here is an example tree:

dir /
    dir_first a /
                  dir second aa
                  dir second ab
                  dir second ac                 
    dir_first b /
                  dir second ba
                  dir second bb
                  dir second bc 
    dir first c /
                  dir second ca
                  dir second cb
                  dir second cc 

I found the way of iterating through the dir here, but this is listing all the second level childrens too and also their full paths, while I want only the directory's name like dir_first a etc.:

$iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($dir_path), 
            RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $file) {
    if($file->isDir()) {
        echo $file->getRealpath();
    }
}
Community
  • 1
  • 1
Ari
  • 4,643
  • 5
  • 36
  • 52

1 Answers1

1

glob allows you to enter a path and then use a flag to return only directories.

$files = glob('mydir/*',GLOB_ONLYDIR);
var_dump($files);
user2182349
  • 9,569
  • 3
  • 29
  • 41
  • o, yes! that is! is there a way to select the output order? I mean ascending or descending? I am still prefer to use the `RecursiveDirectoryIterator`, but I will accept this if this is the only way. – Ari Sep 04 '15 at 03:30
  • The GLOB_NOSORT will return the files in the order listed in the directory. If that doesn't work the way you want it to, you could use PHP's sort functions. – user2182349 Sep 04 '15 at 03:32