note 106840 deleted from function.scandir by danbrown
| From: | danbrown@php.net | Date: | Sun, 11 Dec 2011 19:09:34 +0000 |
| Subject: | note 106840 deleted from function.scandir by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-185021@lists.php.net to get a copy of this message | ||
Note Submitter: support dot REMOVEME at dollarcovers dot com
----
Tweaking donovan dot pp at gmail dot com's excellent submission that avoids recursion and
appears to be 50% faster:
<?php
// sample usage
$filesonlyflag=true;
$fara=dir_tree("/program files", true);
echo "filecount: ".count($fara)."<br>";
function dir_tree($dir, $filesonlyflag=false) {
// TODO: SCANDIR_SORT_NONE not available until PHP 5.4 so
// just allow ascending sort
$SCANDIR_SORT_ASCENDING=0;
// init return array
$fileara=array();
// init stack of directories to traverse
$stack[]=$dir;
// loop until nothing is on the stack
while ($stack) {
// get latest directory added to stack and remove it from stack
$thisdir=array_pop($stack);
// read this directory's files and process them if there are any
// ignore any "Access is denied. (code: 5)" or "failed to open dir: No such file or
directory" or "(errno 2): No such file or directory" errors and move on
if ($dircont=@scandir($thisdir, $SCANDIR_SORT_ASCENDING)) {
// set index to $dircont
$i=0;
// iterate each file or directory in $dircont
while ($i < count($dircont)) {
// ignore . and ..
if ($dircont[$i] !== '.' && $dircont[$i] !== '..') {
// set full file/directory path
$thisfileordir="{$thisdir}/{$dircont[$i]}";
// see if it's a file
if (is_file($thisfileordir)) {
// append it to return array
$fileara[]=$thisfileordir;
} else {
// it's a directory
// see if caller wants directories, too
if (!$filesonlyflag) {
// append this directory also to return array
// add a trailing / so caller can detect difference between file and directory
$fileara[]=$thisfileordir."/";
}
// add this directory to stack
$stack[]=$thisfileordir;
}
}
// next element in $dircont
$i++;
}
}
}
// done
return $fileara;
}
?>
Change log:
optional parameter to return files only (defaults to files and directories)
$path renamed and initialized as an array
@scandir to suppress notices
SCANDIR_SORT_NONE should be faster when available
elseif (is_dir($x)) clause removed (if it's not a file then it must be a directory, right?)
added trailing / to directories so caller can tell the difference between a file and a directory
Apologies:
Please remove if this is deemed "Code collaboration or improvements."
For too many/obvious/PHP newbie code comments.