Dave's Brain

Browse - programming tips - php dir to array

Date: 2008may6
Langauge: PHP

Q.  How do I convert a filesystem directory (folder) to a PHP array?

A.  This function does just that:

function dir_to_array($dir) {
	$a = array();
	if (!($dh = opendir($dir))) return null;
	while (false !== ($node = readdir($dh))) {
		if ($node == '.' || $node == '..') continue;
		$a[] = $node;
        }
	closedir($dh);
	sort($a);
	return $a;
}

# Use like this:

function main() {
	$dir = "/tmp";
	$adir = dir_to_array($dir);
	foreach ($adir as $node) {
		print "- $node\n";
	}
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: