views:

133

answers:

3

Hay all im using a simple look to get file names from a dir

if ($handle = opendir('news_items/')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") { 

        }
    }
}

the files are being outputted news last, oldest first.

How can i reverse this so the newest files are first?

+4  A: 

Get the file list into an array, then array_reverse() it :)

Palantir
Thats what i ended up doing.
dotty
If you are in bad need of customization, or if your array is very large, you could also parse the output of ls commands (or ls | sort, or similar) to get your list. But that requires the possibility to execute shell commands (usually off on shared hosting) and the need to parse them, which will probably reduce the value of such ann approach...
Palantir
Hum I wonder why I did get the "there are new answer" just now as your answer is 19min go.
RC
SO uses some magic to synchronize data, I got notifications and the remaining answers only now...
Palantir
A: 

the simplest option is to invoke a shell command

$files = explode("\n", `ls -1t`);

if, for some reason, this doesn't work, try glob() + sort()

$files = glob("*");
usort($files, create_function('$a, $b', 'return filemtime($b) - filemtime($a);'));
stereofrog
This, of course, makes your code dependent on the platform it runs on, and on your privileges thereon.
xtofl
@xtofl: so what? OP didn't say how (s)he's going to use the code. If you run on a specific platform, it's stupid not to use the power of that platform for the sake of mythical "portability".
stereofrog
A: 

Pushing every files in an array whit mtime as key allow you to reverse sort that array:

<?php

$files = array();

if ($handle = opendir('news_items/')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $mtime = filemtime('news_items/' . $file);

            if (!is_array($files[$mtime])) {
                $files[$mtime] = array();
            }

            array_push($files[$mtime], $file);
        }
    }
}

krsort($files);

foreach ($files as $mt=>$fi) {
    sort($fi);
    echo date ("F d Y H:i:s.", $mt) . " : " . implode($fi, ', ') . "\n";
}

?>
RC