Hongmu Notes
Home Language Notes PHP: Retrieve all directories within a specified directory.
Language Notes PHP

PHP: Retrieve all directories within a specified directory.

PHP: Retrieve all directories within a specified directory.

PHP can be used.scandir()Function Sumis_dir()Use a function to retrieve all directories within a specified directory.

scandir()The function returns an array containing all files and directories in the specified directory.is_dir()This function determines whether a given path is a directory.

The following is an example code that uses these two functions to retrieve all directories within a specified directory:

<?php
// 指定要查找的目录
$dir = "/path/to/directory";

// 使用scandir()函数获取目录中的所有文件和目录
$files = scandir($dir);

// 遍历所有文件和目录,使用is_dir()函数判断是否是目录
foreach ($files as $file) {
    if ($file != "." && $file != ".." && is_dir($dir . "/" . $file)) {
        echo $file . "\n";
    }
}
?>

In the above code,$dirThe variable specifies the directory to search in. Use:scandir()The function retrieves all files and directories from the directory and then uses them.foreachIterate through each file and directory. For each file and directory, useis_dir()Check whether the given string represents a directory; if so, print the directory name. Note that to exclude the current directory (".") and the parent directory (".."), a conditional check should be added during the iteration.$file != "." && $file != ".."

Encapsulate into a function

When you need to use the same code block multiple times, you can encapsulate it into a function so that you can call it whenever needed.

Here is an example code that encapsulates all directory listings from a specified directory into a single function:

function getDirectories($dir) {
    $directories = array();

    if (is_dir($dir)) {
        $files = scandir($dir);

        foreach ($files as $file) {
            if ($file != "." && $file != ".." && is_dir($dir . "/" . $file)) {
                $directories[] = $file;
            }
        }
    }

    return $directories;
}

In this function, we pass a single parameter.$dirThis parameter specifies the path to the directory to be searched. The function first creates an empty array.$directoriesUsed to store the found directory name. Then use it.is_dir()The function checks whether the incoming directory is a valid directory; if so, it is used.scandir()The function retrieves all files and directories within the specified directory. Then, use it.foreachIterate through each file and directory; use.is_dir()Check whether the function represents a directory; if so, add the directory name to the list.$directoriesWithin the array. Finally, the function returns.$directoriesAn array containing all the found directory names.

To call this function, simply pass the path to the directory you wish to search; for example:

$dir = "/path/to/directory";
$directories = getDirectories($dir);

print_r($directories);

The above code will retrieve.$dirAll directories under the current directory, and store them in$directoriesUse the array.print_r()The function is printed out.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 190
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

(Adaptive mobile version) Fire extinguisher – dry powder firefighting equipment; PbootCMS website template; Red firefighting equipment website source code download – 0689

(Adaptive mobile version) Fire extinguisher – dry powder firefighting equipment; PbootCMS website template; Red firefighting equipment website source code download – 0689 Practical Collection pbootcms Template

A PbootCMS red firefighting equipment website template for fire extinguishers and firefighting equipment, compatible with both PC and WAP devices. The eye-catching and professional design is ideal for showcasing firefighting equipment, firefighting devices, and safety solutions. It enables firefighting equipment manufacturers to display their products online, attracting both corporate and government procurement opportunities. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4...
👁 38
Responsive Food & Dessert Cake Website Template 0353

Responsive Food & Dessert Cake Website Template 0353 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the food, dessert, and cake industries. Its warm and inviting design is perfect for showcasing cakes, desserts, gourmet products, brand stories, product ranges, and franchise information. It helps baking brands attract both consumers and franchisees online. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 58
Responsive Beef Noodles Speciality Dish Website Template 1217

Responsive Beef Noodles Speciality Dish Website Template 1217 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the beef noodle and specialty food industries. Its appealing design effectively showcases featured dishes, brand stories, store imagery, and franchise information, helping catering brands attract both customers and franchisees online. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (E...
👁 52
(Adaptive Mobile Version) HTML5 Blue Wide-Screen Clean & Eco-Friendly Tech Energy pbootCMS Corporate Website Template – Responsive Blue Group General Website Source Code Download: 0690

(Adaptive Mobile Version) HTML5 Blue Wide-Screen Clean & Eco-Friendly Tech Energy pbootCMS Corporate Website Template – Responsive Blue Group General Website Source Code Download: 0690 Practical Collection pbootcms Template

A blue widescreen eco-friendly technology-based PbootCMS corporate template featuring responsive design. Its modern, tech-driven aesthetic makes it ideal for showcasing a company's brand identity or business segments in the environmental energy sector or for corporate groups. It is an excellent choice for businesses looking to create an international, high-tech branded official website. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 40
Wellness and滋补保健品 (Deer Antler, Cordyceps-related products) Website Template 0354

Wellness and滋补保健品 (Deer Antler, Cordyceps-related products) Website Template 0354 Practical Collection Yiyou template

An eYouCMS website template designed for the health and wellness supplement industry, as well as the deer antler and cordyceps product sectors. Its health-focused design is ideal for showcasing deer antler and cordyceps products, wellness knowledge, brand stories, and sales information. This template helps supplement brands effectively present their products online and attract health-conscious consumers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: EasyYouCMS Installation Guide...
👁 39
Responsive Travel Agency Website Template 1218

Responsive Travel Agency Website Template 1218 Practical Collection Yiyou template

An eyouCMS responsive website template designed specifically for the tourism and travel agency industry. Its fresh and professional design is ideal for showcasing travel itineraries, attraction descriptions, travel guides and blogs, as well as tourism services. This template helps travel agencies attract online visitors and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eyouCMS | eyouCMS (...
👁 58