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(); } } 
5
  • 1
    If I understand your question right and you need same thing that is output right now but without the full path - use basename. echo basename($file->getRealpath()); Commented Sep 4, 2015 at 3:03
  • isn't it will output the last or in this case the second level directories? Commented Sep 4, 2015 at 3:08
  • so you only need dir_first a, dir_first b, etc? Commented Sep 4, 2015 at 3:09
  • stackoverflow.com/questions/4202175/… Then this is what you need Commented Sep 4, 2015 at 3:11
  • You only need to use the RecursiveDirectoryIterator Commented Sep 4, 2015 at 3:11

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.