PHP OpenDir and sorting results

Hello,
I want to display a directory that contains only PDF’s. I’d like the user to click on a given line and have the appropriate PDF displayed. I copied some code from this site and had to modify it. I put the “breaking return” tag so that each file would be displayed on a separate line. The following code works fine, but I need the file listings to be sorted alphabetically. I’ve tried the sort function for $thelist in several places, but I can’t seem to get it to work. I appreciate your help.

[code]

Untitled Document <?php if ($handle = opendir('hymn_lyrics')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $thelist .= ''.$file.''.'
'; } } closedir($handle); } ?>

List of Hymns:

<?=$thelist?>

[/code]

Shouldn’t it read the files from the dir in alphabetic order?

Anyway, you could read the files / add them to an array, then sort the array and lastly print out the links.

[php] <?php
if ($handle = opendir(‘hymn_lyrics’)) {
while (false !== ($file = readdir($handle)))
{
if ($file != “.” && $file != “…”)
{
$thelist .= ‘’.$file.’’.’
’;
}
}
closedir($handle);
} [/php]–>[php] <?php
$files = array();
if ($handle = opendir(‘hymn_lyrics’)) {
while (false !== ($file = readdir($handle)))
{
if ($file != “.” && $file != “…”)
{
$files[] = $file;
}
}
closedir($handle);
}

asort($files);
foreach ($files as $file) {
echo ‘’.$file.’’.’
’;
}[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service