Question

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;
?>
Was it helpful?

Solution

You can count the items in the array

if (count($files) > 2)

OTHER TIPS

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. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top