title: PHP scandir recursively
body: <p>I'd like my script to scandir recursively,</p>
  
  <pre><code>$files = scandir('/dir');
  foreach($files as $file){
  if(is_dir($file)){
      echo '&lt;li&gt;&lt;label class="tree-toggler nav-header"&gt;&lt;i class="fa fa-folder-o"&gt;&lt;/i&gt;'.$file.'&lt;/label&gt;';
      $subfiles = scandir($rooturl.'/'.$file);
          foreach($subfiles as $subfile){
              // and so on and on and on
          }
          echo '&lt;li&gt;';
      } else {
          echo $file.'&lt;br /&gt;';
      }
  }
  </code></pre>
  
  <p>I'd like to loop this in a way that for each dir found by scandir, it runs another scandir on the folders that have been found within that dir, </p>
  
  <p>So dir 'A' contains dir 1/2/3, it should now scandir(1), scandir(2), scandir(3)
  and so on for each dir found.</p>
  
  <p>How can I manage to implement this easily without copy pasting the code over and over in every foreach?</p>
  
  <p>EDIT: Since the answers are nearly the very same as I already tried, I'll update the question a bit. </p>
  
  <p>With this script I need to create a treeview list. With the current posted scripts the following get's echo'd happens: </p>
  
  <pre><code>/images/dir1/file1.png
  /images/dir1/file2.png
  /images/dir1/file3.png
  /images/anotherfile.php
  /data/uploads/avatar.jpg
  /data/config.php
  index.php
  </code></pre>
  
  <p>What I actually need is:</p>
  
  <pre><code>&lt;li&gt;&lt;label&gt;images&lt;/label&gt;
      &lt;ul&gt;
          &lt;li&gt;&lt;label&gt;dir1&lt;/label&gt;
              &lt;ul&gt;
                  &lt;li&gt;file1.png&lt;/li&gt;
                  &lt;li&gt;file2.png&lt;/li&gt;
                  &lt;li&gt;file3.png&lt;/li&gt;
              &lt;/ul&gt;
          &lt;/li&gt;
          &lt;li&gt;anotherfile.php&lt;/li&gt;
      &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;label&gt;data&lt;/label&gt;
      &lt;ul&gt;
          &lt;li&gt;&lt;label&gt;uploads&lt;/label&gt;
              &lt;ul&gt;
                  &lt;li&gt;avatar.jpg&lt;/li&gt;
              &lt;/ul&gt;
          &lt;/li&gt;
          &lt;li&gt;config.php&lt;/li&gt;
      &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;index.php&lt;/li&gt;
  </code></pre>
  
  <p>And so on, Thank you for the already posted answers!</p>