Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.