Ordering when using PHP to list files

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Rebajas
Forum Newbie
Posts: 16
Joined: Tue Aug 20, 2002 9:35 am
Location: http://www.rebajas.co.uk/

Ordering when using PHP to list files

Post by Rebajas »

When you use PHP to list a bunch of files in a folder, how do you order them and what is the default order?

I presume it is not file name as my results are all over the place... :)

Code: Select all

$path = "/home/sites/site14/web/courses/gallery/";
chdir($path); 
$handle=opendir($path);
while (false!==($file = readdir($handle))) {

	if ($file != "." && $file != ".." && !is_dir($file)) {
		$id = str_replace(".JPG", "", $file);
		$id = str_replace(".jpg", "", $id);
		$text = str_replace("_", " ", $id);

		echo "<img src="/courses/gallery/".$file."" style="width:220px; height:220px; margin:0px 10px 10px 0px; ">\n";
	&#125; 
&#125; 
closedir($handle);
Cheers for any help.


Tony.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

I've noticed this same problem. My naive, uninformed guess would be that PHP just gets the files in the order they are found on the hard disk. I solved the problem by just reading all the filenames into an array, then ordering that array. There is a built in function that just alphabetizes arrays, with the choice to either maintain or lose index associations.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply