Jump to content

[SOLVED] Return Value If Empty Directory


r3p0

Recommended Posts

Howdy,

I use this code to include on one page all HTML files in a directory:

 

<?php

$dir = "directory/subDirectory/";

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
      if(!is_dir($file)) include_once($dir.$file);
        }
        closedir($dh);
    }
}

?>

 

How do I extend this to insert the following code if it finds no files in the directory?

<h1>Directory is empty</h1>
<h2>Thank you please. Come again.</h2>

 

 

Thank you (please)!

 

Link to comment
https://forums.phpfreaks.com/topic/157280-solved-return-value-if-empty-directory/
Share on other sites

<?php

$dir = "directory/subDirectory/";

if (is_dir($dir)) {
    $dirContents = glob($dir . "*");

     if (count($dirContents) > 0) {
         foreach ($dirContents as $file) {
              if(!is_dir($file)) include_once($file);
         }
     }else {
             echo "<h1>Directory is empty</h1>
                     <h2>Thank you please. Come again.</h2>";
     }
}

?>

 

I prefer glob but that is how I roll.

Well since people like displaying code snippets:

$dir = 'directory/subDirectory/';
$files = scandir($dir);
if (!empty($files) && count($files) > 2) echo 'directory not empty';

 

I used !empty() because I personally find count(NULL) to be ridiculous. But you can do it. I prefer not to.

I used !empty() because I personally find count(NULL) to be ridiculous. But you can do it. I prefer not to.

 

Incase that was directed towards my code...

 

glob returns an empty array. So it is not counting a "null" variable, it is counting an array that contains no items. Just an FYI on that.

Because you're counting nothing. It's like me telling you to count the number of marbles when you have no marbles. The situation doesn't even apply.

 

By the way, don't request code snippets. People do them when they feel up to it. But this isn't a request forum. Just letting you know.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.