How to get all the sub-directories of a given directory in PHP?

When you read the content of any specified directory with PHP functions such as scandir() or readdir(), they will return both files and directories. How does one get just the child directories of a given directory in PHP? The obvious solution is the is_dir() function that checks if a filename is a directory:

$all = scandir('.'); // . stands for the current directory, you can use any path string here
$dirs = array();
foreach ($all as $each) {
	if (is_dir($each)) {
		$dirs[] = $each;
	}
}
print_r($dirs);

Which will return:

Array
(
    [0] => .
    [1] => ..
    [2] => dir1
    [3] => dir2
    [4] => dir3
)

Clearly, the problem of this approach is that it also returns ‘.’ and ‘..’.

A better approach is the glob() function that searches the current directory by a certain pattern. You can use it in conjunction with the array_filter() function to select all the directories:

$dirs = array_filter(glob('*'), 'is_dir'); // is_dir function is used against each item of the array returned by glob('*')
print_r($dirs);

Which will give out results:

Array
(
    [0] => dir1
    [1] => dir2
    [2] => dir3
)

A neater way to get the same results with glob() function is this:

$dirs = glob('*', GLOB_ONLYDIR);
print_r($dirs);

The GLOB_ONLYDIR flag commands the function to return only directory entries that match the pattern ‘*’.

1 thought on “How to get all the sub-directories of a given directory in PHP?”

  1. Thanks anyway, I didnt know about glog() function.
    Does it take “the space in the dir name” into consideration?
    E.g. if a directory is something like “New Folder”, will if function as expected?

Comments are closed.

Scroll to Top