Home > Backend Development > PHP Tutorial > How to Retrieve Subdirectories from a Given Directory in PHP?

How to Retrieve Subdirectories from a Given Directory in PHP?

Linda Hamilton
Release: 2024-11-17 04:25:03
Original
495 people have browsed it

How to Retrieve Subdirectories from a Given Directory in PHP?

Retrieving Subdirectories from a Given Directory in PHP

Determining the subdirectories present within a specified directory often arises as a requirement in PHP programming. To effectively handle this task, you can leverage either the glob() function or a combination of glob() and array_filter().

Option 1: Utilizing glob() with GLOB_ONLYDIR

The glob() function, when used with the GLOB_ONLYDIR flag, offers a straightforward approach. This flag excludes files and the current (.), parent (..), and any directories beginning with a period (.), ensuring you solely obtain the subdirectories:

$subdirectories = glob('path/to/directory/*', GLOB_ONLYDIR);
Copy after login

Option 2: Leveraging array_filter() to Refine Results

Alternatively, you can combine glob() and array_filter() to filter out files and unwanted directories. However, this method may overlook directories that contain periods in their names, such as .config.

$directories = glob('path/to/directory/*');
$subdirectories = array_filter($directories, 'is_dir');
Copy after login

Applying the Function to Each Subdirectory

Once you have retrieved the subdirectories, you can apply a function to each of them using a loop:

foreach ($subdirectories as $subdirectory) {
    myFunction($subdirectory);
}
Copy after login

By employing either of these options, you can efficiently gather the subdirectories within a specified directory and utilize them in your PHP code as needed.

The above is the detailed content of How to Retrieve Subdirectories from a Given Directory in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template