Search code examples
phpdirectoryreaddiropendir

php list directory 5 files at-a-time


I am trying to pull all of the files in a directory, but do it in 5-filename chunks. I can't find an example that doesn't use the while (($file = readdir($dh)) !== false) loop. I thought there used to be a statement similar to this while(!feof($file)) but for directories, but I can't find it anymore. Any help is appreciated.

This is my best attempt:

$dir = "images";
opendir($dir);

while (($file = readdir($dh)) !== false)
{

for ($x=0; $x<=5; $x++)
{
$file = readdir($dh);
echo $file . '<br>';
}

}
closedir($dir);

Thanks,

Doug


Solution

  • What about

    $dir = "images";
    opendir($dir);
    $continue=true;
    
    while ($continue) {
      for ($x=0; $x<=5; $x++) {
        $file = readdir($dh);
        if ($file===false) {
          $continue=false; //for the while
          break;           //for the for
        }
        echo $file . '<br>';
      }
    }
    
    closedir($dir);
    

    You could remove the need for the $continue flag variable by using while($file!==false) but at a cost on readability.