Sorting directory entries

Hi.
I have the feeling this should be easy but I have tried various ways without success.
Basically I have a directory containing pdf documents. I want to download the file names and display them in the order they appear in the directory, or in date order, either will do. The idea is to be able to add the documents to the directory and not have to modify and other code to allow them to be downloaded.
I can get the list OK but this is not in the same order as in the directory and I can’t see how it is ordered. If I knew that I could modify the file names accordingly (I’ve tried adding numbers and dates to the file name without any luck).
Here’s the code I use to get the list…

$dir=dir(‘downloads’);
while ($document=$dir->read()){
$ext = explode(‘.’,$document);
$size = count($ext);
if ($ext[$size-1] ==‘pdf’)
{

$docname=$ext[0];

echo(“<li><a href=‘downloads/$document’ target=‘_blank’>$docname</a></li>”);
}

}

I know PHP has some string sort functions but I thought this should be possible without using them.

$dir=dir('downloads');

while ($document=$dir->read()) 
{
	$ext = explode('.',$document);
	$size = count($ext);

	$output = array();
	
	if ($ext[$size-1] =='pdf') 
	{
	
		$docname=$ext[0];
	
		// Build an array of associative names.
		$output[$docname];
	
	}
	

}

// there are many other sorts 
//http://php.net/manual/en/array.sorting.php
sort($output); 

// Loop through the array of names..
foreach ($output as $key => $val)
{
	echo "<li><a href='downloads/$key.pdf' target='_blank'>$key</a></li>";
}

Excellent. Thanks for such a quick response. I was just a little put off by converting to an array to do the sort. I didn’t realize it was that easy as I rarely need to use arrays.

Once again thanks for your help.

John.

You could also use glob() to get an array of the PDF files in that folder. Glob sorts the files alphabetically by default.


$pdfs = glob("downloads/*.pdf");
foreach ($pdfs as $pdf) 
{
    $file = basename($pdf, ".pdf"); // get "bob" from "downloads/bob.pdf"
    echo "<li><a href='downloads/$file.pdf' target='_blank'>$file</a></li>"; 
}

Don’t neglect arrays! They are in my opinion the most important thing you can learn.

Glob returns an array, what’s the problem? :blush:

Was talking to the other guy sorry :stuck_out_tongue:

thanks.
glob() is so much easier and cleaner, I don’t know why I didn’t think of that.
Sorry to cause an argument amongst you guys but I appreciate the help.
John.