Re: Sorting files in a directory

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Steve Marquez wrote:
I know this code does not work, but I was curious if someone can take a look
and tell me what is wrong? Thank you so much.
Re-indent your code properly. If you do it will look like:

<?php
$pattern = ".html*|.php*";

if (is_dir("files/")) {
   if ($dh = opendir("files/")) {
       echo "<select name=\"file\" size=\"8\">";
       while (($file = readdir($dh)) !== false) {
           if (ereg($pattern, $file))
               if(strpos($file,'.')>0) {
                   $file_array = array($file);
                   sort ($file_array);

                   foreach($file_array as $key => $value) {
                       echo "<option value=\"$value\">".$value."</option>";
                   }
               }
           }
           echo "</select>";
           closedir($dh);
       }
   }
?>

You have a number of things you need to look at here. First, you don't have a final closing brace for your opening if() statement. Second, you're outputting the <option> tags INSIDE the while loop that reads the directory, so for every file you read your options list will get bigger. Well, it would, but you're also not using the right array append method; it should be:
                   $file_array[] = $file;

Next, you don't want to sort the array every time you add a file to it - just do it once when you're done.

Try this:
<?php
$pattern = ".html*|.php*";

if (is_dir("files/") && $dh = opendir("files/")) {
   echo '<select name="file" size="8">';
   while (($file = readdir($dh)) !== false) {
       if (!ereg($pattern, $file)) continue;
       if(strpos($file,'.')<1) continue;
       $file_array[] = $file;
   }

   sort ($file_array);
   foreach($file_array as $value) {
       echo '<option value="' . $value . '">' . $value . '</option>';
   }
   echo "</select>";
   closedir($dh);
}
?>

Syntax check is left as an exe3rcise for the student. =)

Regards,
Chad

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux