【问题标题】:How to check,that there's nothing in the folder?怎么查,文件夹里面什么都没有?
【发布时间】:2014-05-08 12:18:09
【问题描述】:

我想检查文件夹是否为空。我试过$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;
?>

【问题讨论】:

标签: php directory scandir


【解决方案1】:

您可以统计array中的项目

if (count($files) > 2)

【讨论】:

  • 它适用于 If (count($files) > 2) 但这些 2 是什么。和 .. 在数组中?
  • 我不确定它们为什么会出现。如果您希望 array 仅包含实际文件,则可以将变量分配给 array_diff(scandir($directory), array('..', '.')); :-)
【解决方案2】:

使用这个:

$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。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多