Skip to content

Instantly share code, notes, and snippets.

@davidrautert
Created February 1, 2011 19:16
Show Gist options
  • Save davidrautert/806423 to your computer and use it in GitHub Desktop.
Save davidrautert/806423 to your computer and use it in GitHub Desktop.
Recursively scan files and folders in a directory, building into either a multidimensional array or flattened array of full paths
function foldersToArray($path, $flat = false) {
$folderArray = array();
if($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if($file != '.' && $file != '..') {
if(!in_array($path.'/'.$file, $folderArray) && is_file($path.'/'.$file)) {
if($flat) {
array_push($folderArray, $path.'/'.$file);
} else {
array_push($folderArray, $file);
}
} else if(!in_array($file, $folderArray) && is_dir($path.'/'.$file)) {
if($flat) {
$sandbox = foldersToArray($path.'/'.$file, $flat);
$folderArray = array_merge($folderArray, $sandbox);
} else {
$folderArray[$file] = foldersToArray($path.'/'.$file, $flat);
}
}
}
}
}
return $folderArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment