title: Rename function not working as expected
body: <p>I'm using PHP to batch rename some local photos. The script is in the same directory as the photos.</p>
  
  <p>The photos are named like <code>872376237_Photo_1_001.jpg</code>. The first set of numbers (before the first underscore) is different for each file, and that's what I want to remove.</p>
  
  <p>The format for the new file name should be <code>Photo_1_001.jpg</code>. In the PHP I get the new file name by using <code>$newfilename = substr($filename, strpos($filename, '_') + 1);</code>. Echo'ing out <code>$newfilename</code> shows the correct new file name.</p>
  
  <p>The problem is when I call <code>rename($filename, $newfilename)</code> the files are getting renamed to <code>1_001.jpg</code>. The <code>$newfilename</code> variable definitely contains the correct new file name. If I use <code>copy()</code> instead of <code>rename()</code> it works as expected. I can't figure this out.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>$dir = new DirectoryIterator(dirname(__FILE__));
  
  foreach ($dir as $fileinfo) {
      if (!$fileinfo-&gt;isDot()) {
          $filename = $fileinfo-&gt;getFilename();
          if ($filename != basename(__FILE__)) { // skip this script
              $newfilename = substr($filename, strpos($filename, '_') + 1);
              rename($filename, $newfilename);
          }
      }
  }
  </code></pre>
  
  <p><strong>EDIT</strong>: DevZer0 explained why this is happening in the comments. I thought DirectoryIterator compiled a list of all the files before iterating, but it does not. It will continuously iterate as long as new files are created (or renamed).</p>
  
  <p>There's probably a better way to do this, but this works:</p>
  
  <pre><code>$dir = new DirectoryIterator(dirname(__FILE__));
  $filenames = [];
  
  foreach ($dir as $fileinfo) {
      if (!$fileinfo-&gt;isDot()) {
          $filename = $fileinfo-&gt;getFilename();
  
          if ($filename != basename(__FILE__)) {
              $newfilename = substr($filename, strpos($filename, '_') + 1);
              array_push($filenames, [$filename, $newfilename]);
          }
      }
  }
  
  foreach ($filenames as $file) {
      rename($file[0], $file[1]);
  }
  </code></pre>