views:

53

answers:

5

How would I list all the files and folders in a folder alphabetically with PHP. I used the following for the files a.txt, b.txt, c, d.txt. Where c is a folder.

The problem is that c is displayed last instead of after b.txt because it is a folder.

I'd also like to be able to check if each is either a file or folder.

<?php
$dir = opendir ("folders");
        while (false !== ($file = readdir($dir))) {
            echo "$file <br />";
        }
?>
A: 

Just read the names into an array first instead of printing immediately. Then sort the array, and then do your output.

<?php
$dir = opendir ("folders");
while (false !== ($file = readdir($dir))) {
    $names[] = $file;
}
sort($names, SORT_STRING);
foreach ($names as $name) {
    echo "$name <br />";
}
?>
Chad Birch
A: 
<?php
$files = array();
$dir = opendir ("folders");
while (false !== ($file = readdir($dir))) {
    $files[] = $file;
}
sort($files);

foreach ($files as $f)
    echo "$f <br />";

?>

jackbot
+1  A: 

Power of glob() is here to help you. just

$dir=glob("folders/*");

will do the thing

Col. Shrapnel
How could you check which ones are folders?
usertest
Use the `is_file($filename)` and `is_dir($filename)` functions.
Chad Birch
glob has several parameters, so, you can use it twice, first for the folders and next for the files. or use is_file() and is_dir() mentioned above.http://php.net/glob for the more info(PHP folks have very useful url shortcuts)
Col. Shrapnel
A: 

I would suggest the following code (no need for opendir etc.)

$entries = glob("*");
sort($entries); // This is optional depending on your os, on linux it works the way you want w/o the sort
var_dump($entries);

/* Output
array(4) {
  [0]=>
  string(5) "a.txt"
  [1]=>
  string(5) "b.txt"
  [2]=>
  string(1) "c"
  [3]=>
  string(5) "d.txt"
}
*/

For the secound part of your question: You the php "is_file" and "is_dir" functions

edorian
A: 
$files = scandir('folders');
sort($files);
foreach ($files as $file) {
    echo $file.'<br />';
}
henasraf