使用 PHP 返回文件夹内的文件总数 [英] Return total number of files within a folder using PHP

查看:31
本文介绍了使用 PHP 返回文件夹内的文件总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好/更简单的方法来查找目录中的图像数量并将它们输出到变量?

Is there a better/simpler way to find the number of images in a directory and output them to a variable?

function dirCount($dir) {
  $x = 0;
  while (($file = readdir($dir)) !== false) {
    if (isImage($file)) {$x = $x + 1}
  }
  return $x;
}

这样的方法好像很长,有没有更简单的方法?

This seems like such a long way of doing this, is there no simpler way?

注意:如果文件是图像,isImage() 函数返回 true.

Note: The isImage() function returns true if the file is an image.

推荐答案

查看 DirectoryIterator 的标准 PHP 库(又名 SPL):

Check out the Standard PHP Library (aka SPL) for DirectoryIterator:

$dir = new DirectoryIterator('/path/to/dir');
foreach($dir as $file ){
  $x += (isImage($file)) ? 1 : 0;
}

(仅供参考,有一个名为 iterator_count() 的未记录函数,但我想现在最好不要依赖它.而且你需要过滤掉看不见的东西,比如 . 和 .. 无论如何.)

(FYI there is an undocumented function called iterator_count() but probably best not to rely on it for now I would imagine. And you'd need to filter out unseen stuff like . and .. anyway.)

这篇关于使用 PHP 返回文件夹内的文件总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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