Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get all subdirectories of a given directory

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?

like image 550
Adrian M. Avatar asked Oct 16 '22 15:10

Adrian M.


People also ask

How can I get a list of all the subfolders and files present in a directory using PHP?

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.

How do I get all subdirectories?

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

How to read folder in PHP?

PHP readdir() Function The readdir() function returns the name of the next entry in a directory.

What does Scandir do in PHP?

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.


1 Answers

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);
like image 241
ghostdog74 Avatar answered Oct 18 '22 03:10

ghostdog74