Home  >  Article  >  Backend Development  >  Why are there two more divs every time?

Why are there two more divs every time?

WBOY
WBOYOriginal
2016-08-18 09:16:061356browse

I put a div outside. Why are there two more empty divs? Why do there always appear two more empty divs every time? What is the reason for this? How can I remove it?
Why are there two more divs every time?

<code>$dir = "upload/"; 
    if (is_dir($dir)){
       if ($dh = opendir($dir)){
         while (($file = readdir($dh))!= false){
            echo '<div>';
            if (!is_dir($file)) {
              $filePath = $dir.$file;
              echo "<img src='".$filePath."'/>";
            }
            echo '</div>';
         }
        closedir($dh);
       }
    }</code>

Reply content:

I put a div outside. Why are there two more empty divs? Why do there always appear two more empty divs every time? What is the reason for this? How can I remove it?
Why are there two more divs every time?

<code>$dir = "upload/"; 
    if (is_dir($dir)){
       if ($dh = opendir($dir)){
         while (($file = readdir($dh))!= false){
            echo '<div>';
            if (!is_dir($file)) {
              $filePath = $dir.$file;
              echo "<img src='".$filePath."'/>";
            }
            echo '</div>';
         }
        closedir($dh);
       }
    }</code>

Print it

<code>print_r(readdir($dh));</code>

You know why.

readdir will print out . and .., so your echo "

" should be placed inside if !is_dir

The two extra ones should be . for the current directory and . for the upper-level directory. Just filter these two out

Just make a ifjudgment

<code class="php">
$dir = "upload/"; 
if (is_dir($dir)){
   if ($dh = opendir($dir)){
     while (($file = readdir($dh))!= false){
        if (!is_dir($file)) {
        
          //. 和.. 在文件夹下,不管在什么系统中. 和..都是存在的, .指向当前目录, ..上一级目录
          if ($file === '.' || $file === '..') {
              continue;
          }
          
          echo '</div>';
          $filePath = $dir.$file;
          echo "<img src='".$filePath."'/>";
          echo '</div>';
        }
        
     }
    closedir($dh);
   }
}
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn