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 !== ($file = readdir($dh))) {
		if ($file == '.' || $file == '..') continue;
		$a[] = $file;
        }
	closedir($dh);
	sort($a);
	return $a;
}

# Use like this:

function main() {
	$dir = "/tmp";
	$adir = dir_to_array($dir);
	foreach ($adir as $file) {
		print "- $file\n";
	}
}

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.