"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Find Subdirectories in PHP?

How to Find Subdirectories in PHP?

Posted on 2025-03-22
Browse:523

How to Find Subdirectories in PHP?

Finding Subdirectories in PHP

Retrieving a list of subdirectories within a specified directory is a common operation in web development. In PHP, you can accomplish this task in several ways.

Option 1: Using glob() with GLOB_ONLYDIR

The glob() function can be employed with the GLOB_ONLYDIR flag to select only directories. This technique ensures that files, the current directory, and the parent directory are excluded from the results:

$subdirectories = glob('directory/*', GLOB_ONLYDIR);
foreach ($subdirectories as $subdirectory) {
    // Process each subdirectory
}

Option 2: Filtering with array_filter

Alternatively, you can use array_filter() to filter the list of directories. However, be mindful that this approach skips directories containing periods within their names (like ".config"):

$entries = scandir('directory');
$directories = array_filter($entries, 'is_dir');
foreach ($directories as $directory) {
    // Process each directory
}

By leveraging either of these methods, you can efficiently obtain all subdirectories of a specified directory in PHP and proceed with further processing or operations within your code.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3