0

I have the following code which outputs the contents of text files held in a directory.

Ive been looking at the sort command in PHP but cant get it to work with the following code, I usually get an error about the input being a string and not an array.

How can I sort the directory of file before they are output?

   $directory = "polls/";
    $dir = opendir($directory);


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

      $filename = $directory . $file;
      $type = filetype($filename);
      if ($type == 'file') {
      $contents = file_get_contents($filename);
      list($tag, $name, $description, $text1, $text2, $text3, $date) = explode('¬', $contents);

      echo '<table width="500" border="1" cellpadding="4">';
      echo "<tr><td>$tag</td></tr>\n";
      echo "<tr><td>$name</td></tr>\n";
      echo "<tr><td>$description</td></tr>\n";
      echo "<tr><td>$text1</td></tr>\n";
      echo "<tr><td>$text2</td></tr>\n";
      echo "<tr><td>$text3</td></tr>\n";
      echo "<tr><td>$date</td></tr>\n";
      echo '</table>';

      }
    }
    closedir($dir);

3 Answers 3

3

First collect the entries in an array, sort it and then put it out:

$directory = "polls/";
$dir = opendir($directory);
$files = array();
while (($file = readdir($dir)) !== false) {
    $files[] = $file;
}
closedir($dir);
sort($files);

foreach ($files as $file) {
    // content of your original while loop
}
Sign up to request clarification or add additional context in comments.

1 Comment

I changed the sort to: sort($files,SORT_NUMERIC); as the files are all named numerically.
1

Another possibility is fetching the file names with glob(). Its output is sorted by default.

<?php

foreach(glob('polls/*.txt') as $file){
    // ...
}

?>

Comments

0

Don't print it in the while loop, but store it in an array. Sort the array and then print it.

(On php.net you'll find enough different sorting functions to get the sorting method you need.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.