How can a recursive function in PHP be used to read all sub-folders of a directory and store them in an array?
To read all sub-folders of a directory and store them in an array using a recursive function in PHP, we can create a function that iterates through all the files and folders in a directory. When a sub-folder is encountered, the function can call itself recursively to read its contents as well. This way, we can build an array containing all the sub-folders within a directory.
function readSubFolders($dir) {
$subFolders = [];
$files = scandir($dir);
foreach($files as $file) {
if ($file == '.' || $file == '..') {
continue;
}
$fullPath = $dir . '/' . $file;
if (is_dir($fullPath)) {
$subFolders[] = $fullPath;
$subFolders = array_merge($subFolders, readSubFolders($fullPath));
}
}
return $subFolders;
}
$directory = 'path/to/directory';
$subFoldersArray = readSubFolders($directory);
print_r($subFoldersArray);
Keywords
Related Questions
- In what situations is it beneficial to use $_SERVER['QUERY_STRING'] in PHP, and how can it be effectively integrated with other parameters?
- How can PHP developers effectively transfer functions between classes without encountering issues like $this in static functions?
- How can one efficiently read only the first 200 characters of a file in PHP?