Forum Moderators: coopster

Message Too Old, No Replies

File sorting problem

Different sorts

         

Jumper Willow

5:16 pm on Aug 24, 2004 (gmt 0)

10+ Year Member



Here's the snippet of relevant code to start:

if ($handle = opendir($Path)) {
while (false!== ($file = readdir($handle)) && $break == false) {
if ($file!= "." && $file!= ".."){
echo $file;
}
}
closedir($handle);
}

I got the bulk of this code off of the main php site under the file() function list I believe. It has been working wonders with making the development process easier, but I've noticed something after using it in a different application.

The code will run perfectly on my remote webserver and on my local machine (using easyPHP). The only difference is on my local machine, the files will be output in "ascii-bit" order (a, b, c...). On the remote server when I put the files though, the code will run and the files are sorted in the order that they were uploaded (as far as i've been able to tell).

It's not a big hassle to re-upload the files starting with z and going back to a for them to be listed in order, but I was curious as to what might cause it, if anyone else has had the same "effect," if it's just a "feature" of PHP, etc...

Birdman

5:50 pm on Aug 24, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Jumper Willow. Never underestimate the user comments from the PHP manual. There is valuable info down there, including the answer to your prob.

I ran into a little snag in example 1. opendir() lists files by the last time the file was accessed. I was trying to print the files numerically in a directory.

Solution: Use scandir() instead (php5) or store the files in an array and sort it.

Since there's a good chance youu don't have PHP5, here's how it would go using the array method:

if ($handle = opendir($Path)) {
while (false!== ($file = readdir($handle)) && $break == false) {
if ($file!= "." && $file!= ".."){
$files[] = $file; // build the array
}
}
closedir($handle);
}

sort($files);

foreach ($files as $val) echo $val . "\r\n";

Regards

Jumper Willow

9:15 pm on Aug 24, 2004 (gmt 0)

10+ Year Member



Thanks alot. I read through them, but I guess it just didn't stick.