jesse1981
4/20/2013 - 3:44 PM

PHP function to return a directory tree to an array.

PHP function to return a directory tree to an array.

function directoryToArray($directory, $recursive) {
    $array_items = array();
    if ($handle = opendir($directory)) {
        while (false !== ($file = readdir($handle))) {
            if (($file != "." && $file != "..") && 
                (is_dir($directory. "/" . $file)) && 
                ($recursive)) $array_items = array_merge($array_items, 
                                                        directoryToArray($directory. "/" . $file, $recursive));
            if (is_dir($directory. "/" . $file)) {
                    $file = $directory . "/" . $file;
                    $array_items[] = preg_replace("/\/\//si", "/", $file);
            } 
            else {
                    $file = $directory . "/" . $file;
                    $array_items[] = preg_replace("/\/\//si", "/", $file);
            }
        }
        closedir($handle);
    }
    return $array_items;
}