How can I get all sub-directories of a given directory without files, .
(current directory) or ..
(parent directory)
and then use each directory in a function?
PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.
- If you want to get all immediate subdirectories for a folder use os. scandir . - If you want to get all subdirectories, even nested ones, use os. walk or - slightly faster - the fast_scandir function above.
PHP readdir() Function The readdir() function returns the name of the next entry in a directory.
The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.
Option 1:
You can use glob()
with the GLOB_ONLYDIR
option.
Option 2:
Another option is to use array_filter
to filter the list of directories. However, note that the code below will skip valid directories with periods in their name like .config
.
$dirs = array_filter(glob('*'), 'is_dir');
print_r($dirs);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With