Date: 2008may6
Updated: 2016nov26
Langauge: PHP
Q. PHP: convert a filesystem directory (folder) to a php array
A.
In php5:
function dir_to_array($dir) {
return array_diff(scandir($dir), array('..', '.'));
}
Before php5:
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";
}
}