Jump to content

While loops and readdir() function problem


essjay_d12

Recommended Posts

I am trying to oder folders before files when i display a directory through php.

 

Though they do not seem to work with the following code .... anyone see what's wrong?

 

if (is_dir($dir)){
if ($dh = opendir($dir)) {

              // removes two hidden files "." and ".."
              if($file != "." && $file != "..") {

	  while ((($file = readdir($dh)) !== false) && (filetype($dir . $file) == "dir" )) {

			echo $file;
                                echo 'folder';
	  }

	  while ((($file = readdir($dh)) !== false) && (filetype($dir . $file) == "file" )) {

           			echo $file;
                                echo 'file';


		}

	}
}
closedir($dh);
}

 

cheers

 

d

Link to comment
https://forums.phpfreaks.com/topic/51666-while-loops-and-readdir-function-problem/
Share on other sites

Both your loops have the same 1st condition, so once the first loop finishes the second loop will obviously never execute.

 

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

 

You need to reopen the directory between your loops like so:

 

if (is_dir($dir)){
if ($dh = opendir($dir)) {

              // removes two hidden files "." and ".."
              if($file != "." && $file != "..") {

	  while ((($file = readdir($dh)) !== false) && (filetype($dir . $file) == "dir" )) {

			echo $file;
                                echo 'folder';
	  }

          closedir($dh);
                  $dh = opendir($dir); // Reopen the directory

	  while ((($file = readdir($dh)) !== false) && (filetype($dir . $file) == "file" )) {

           			echo $file;
                                echo 'file';


		}

	}
}
closedir($dh);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.