如何使用PHP计算目录中的文件数? [英] How to count number of files in a directory using PHP?

查看:27
本文介绍了如何使用PHP计算目录中的文件数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to count the number of files in a directory using PHP?

请回答以下问题:

1.递归搜索:(正在搜索的)目录可能有其他几个目录和文件.

1. Recursive Search: The directory (which is being searched) might be having several other directories and files.

2.非递归搜索:应忽略正在搜索的目录内的所有目录.只考虑文件.

2. Non-Recursive Search: All the directories should be ignored which are inside the directory that is being searched. Only files to be considered.

我有以下代码,但正在寻找更好的解决方案.

I am having the following code, but looking for a better solution.

<?php

     $files = array();
     $dir = opendir('./items/2/l');
     while(($file = readdir($dir)) !== false)
     {
          if($file !== '.' && $file !== '..' && !is_dir($file))
          {
               $files[] = $file;
          }
     }
     closedir($dir);
     //sort($files);
     $nooffiles = count($files);
?>

推荐答案

非递归:

$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";

这篇关于如何使用PHP计算目录中的文件数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆