Never been to DZone Snippets before?

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

Get (recursive) directory listing in array (See related posts)

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 on this post

HotFusionMan posts on Feb 26, 2008 at 09:30
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);
          }
...
HotFusionMan posts on Feb 26, 2008 at 09:34
Furthermore, default argument values would make it nicer to use:

function directoryToArray( $directory, $recursive = false, $include_directories_in_list = true ) {
...

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts