DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Get (recursive) Directory Listing In Array

04.13.2005
| 67460 views |
  • submit to reddit
        Updated to include drwitt's fix. Shame on me! Well, as long as I learn from my mistakes :)

Get a (recursive) directory listing in an array. Directory's are included in this list. If this behavior is not wanted, remove the two lines:

$file = $directory . "/" . $file;
$array_items[] = preg_replace("/\/\//si", "/", $file);

To get a non recursive directory listing, use it like this:

$files = directoryToArray("./", false);

And to get a recursive directory listing, use it like this:

$files = directoryToArray("./", true);

Once you have an array of files, you can iterate over the directories/files like this:

echo '<ul>';

foreach ($files as $file) {
	echo '<li>' . $file . '</li>';
}

echo '</ul>';

or like this:

echo '<ul>';

for ($i = 0; $i <= count($files); $i++) {
	echo '<li>' . $files[$i] . '</li>';
}

echo '</ul>';

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

Hope someone can use it!    

Comments

Albert Chou replied on Mon, 2007/08/20 - 8:22pm

Furthermore, default argument values would make it nicer to use: function directoryToArray( $directory, $recursive = false, $include_directories_in_list = true ) { ...

Albert Chou replied on Mon, 2007/08/20 - 8:22pm

How about making the "include directories in the list" option an argument to the function? function directoryToArray( $directory, $recursive, $include_directories_in_list ) ... if (is_dir($directory. "/" . $file)) { ... if ( $include_directories_in_list ) { $file = $directory . "/" . $file; $array_items[] = preg_replace("/\/\//si", "/", $file); } ...