Why are there two more divs every time?

WBOY
Release: 2016-08-18 09:16:06
Original
1403 people have browsed it

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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

Print it

<code>print_r(readdir($dh));</code>
Copy after login

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>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template