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 ‘*’.
You should also read:
- PHP: Display Files and Sub-directories of A Directory Recursively as A Tree
- Linux: Check how much disk storage each directory takes up (Disk Usage command – du)
- PHP: Check or Validate URL and Email Addresses – an Easier Way than Regular Expressions, the filter_var() Function
- PHP: Crontab Class to Add, Edit and Remove Cron Jobs
- PHP: How to detect / get the real client IP address of website visitors?


Facebook
Twitter
Google Plus
{ 1 comment… read it below or add one }
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?