php read directory sorting

Piet Bez picture Piet Bez · Aug 7, 2013 · Viewed 19.3k times · Source

i have a little php script that reads a directory and then echos all the files (jpg's in this case) into a jquery image slider. it works perfectly, but i dont know how to sort the images by name desending. at the moment the images are random.

<?php
$dir = 'images/demo/';
if ($handle = opendir($dir)) {

while (false !== ($file = readdir($handle))) {
    echo '<img src="'.$dir.$file.'"/>';
}

closedir($handle);
}
?>

any help on this would be great.

one more thing i dont understand. the script pics up 2 nameless non jpg files in that folder that does not exist??? but i havnt realy checked into that yet

Answer

Manoj Yadav picture Manoj Yadav · Aug 7, 2013

Try this:

$dir = 'images/demo/';
$files = scandir($dir);
rsort($files);
foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        echo '<img src="' . $dir . $file . '"/>';
    }
}