tags:

views:

298

answers:

2

Im currently outputting all text files held in a directory:

$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);

I would like to extend this so that the files are sorted before output, there unixtime format filenames so aphabetically should do it. Then I only want to output the first 5 after they have been sorted. That should give me the latest 5.

A: 

Well, if the data is not already sorted, you have to build an array of files, sort them with sort and then use array_slice to extract the first five items.

Joey
Is it possible you could show me an example of how i might achieve this?
danit
A: 

You could instead make use of glob (which sorts the files in ascending order) and just extract a slice of that array of file paths. For example:

$files   = glob('polls/[0-9]*.txt');
$reverse = array_reverse($files);
$latest  = array_slice($reverse, 0, 10);
foreach ($latest as $file) {
    // ...
}
salathe