且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用PHP计算目录中的文件数?

更新时间:2022-12-09 20:27:38

非递归:

$dir = opendir('dir/');
$i = 0;
while (false !== ($file = readdir($dir))){
    if (!in_array($file, array('.', '..') and !is_dir($file)) $i++;
}

echo "There were $i files";

递归:

function crawl($dir){

    $dir = opendir($dir);
    $i = 0;
    while (false !== ($file = readdir($dir)){
            if (is_dir($file) and !in_array($file, array('.', '..'))){

            $i += crawl($file);
        }else{
            $i++;
        }

    }
    return $i;
}
$i = crawl('dir/');
echo "There were $i files";