如何检查,文件夹中没有任何内容?

时间:2014-03-28 20:50:26

标签: php directory scandir

我想检查文件夹是否为空。我尝试了$files!=0,但它不起作用,因为print_r($files);显示了这一点:Array ( [0] => . [1] => .. )如何写出正确的条件?

<?php
$folder = "images/thumbs/";
$files  = scandir($folder);

if ("the folder is not empty") {
    $output = "<div>";
    foreach ($files as $file) {
        if (substr($fajl, -4) == ".jpg" || substr($fajl, -4) == ".png" || substr($fajl, -4) == ".gif") {
            $output .= "<img src=\"{$folder}{$file}\" alt=\"\">";
        }
    }
    $output .= "</div>";
} else {
    $output = "<p>There are no thumbnails in the folder.</p>";

}
return $output;
?>

2 个答案:

答案 0 :(得分:2)

您可以计算array

中的项目
if (count($files) > 2)

答案 1 :(得分:0)

使用此:

$c=0;
     foreach(glob($folder.'*.*') as $filename){
     $c++;
 }
if($c==0){$output = "<p>There are no thumbnails in the folder.</p>";}

或者只是计算它们并像这里更新$output

<?php
$folder = "images/thumbs/";
$files  = scandir($folder);
$output = "<div>";
foreach ($files as $file) {
        if (substr($fajl, -4) == ".jpg" || substr($fajl, -4) == ".png" || substr($fajl, -4) == ".gif") {
            $output .= "<img src=\"{$folder}{$file}\" alt=\"\">";
        }
    }
    $output .= "</div>";
    if($output=="<div></div>"){$output = "<p>There are no thumbnails in the folder.</p>";}

return $output;
?>

你甚至不需要那个旧if。 :)