0

I would like to check if the folder is empty or not. I tried $files!=0 but it doesn't work,because the print_r($files); shows this: Array ( [0] => . [1] => .. ) How to write the right condition?

<?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;
?>
Patrick Reck
  • 11,246
  • 11
  • 53
  • 86
darksoul90
  • 145
  • 2
  • 16
  • did u check this ? http://stackoverflow.com/questions/7497733/how-can-use-php-to-check-if-a-directory-is-empty – Abhik Chakraborty Mar 28 '14 at 20:52
  • If you are interested only in specific files (with extensions .jpg, .gif, .png) you can use `glob` instead of `scandir` as described here: http://stackoverflow.com/questions/10591530/php-file-listing-multiple-file-extensions – mesutozer Mar 28 '14 at 20:56

2 Answers2

2

You can count the items in the array

if (count($files) > 2)
Patrick Reck
  • 11,246
  • 11
  • 53
  • 86
  • It works with If (count($files) > 2) but what are these 2 . and .. in the array? – darksoul90 Mar 28 '14 at 21:15
  • I am not sure why they appear. If you want the `array` to only contain the actual files, you can assign the variable to `array_diff(scandir($directory), array('..', '.'));` instead :-) – Patrick Reck Mar 28 '14 at 21:33
0

Use this:

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

Or simply count them and update the $output like here:

<?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;
?>

And you dont even need that old if. :)

artur99
  • 818
  • 6
  • 18