Question

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

Was it helpful?

Solution

Try this:

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

OTHER TIPS

Try putting each item in an array and then sorting that:

$images = array();

while (false !== ($file = readdir($handle))) {
    $images[] = $file;
}

natcasesort($images);

foreach ($images as $file) {
    echo '<img src="'.$dir.$file.'"/>';
}

EDIT:

sorting version using the asort() function.

asort() ascending order - arsort() reverse order

<?php

// You can use the desired folder to check and comment the others.
// foreach (glob("../downloads/*") as $path) { // lists all files in sub-folder called "downloads"
foreach (glob("images/*.jpg") as $path) { // lists all files in folder called "test"

    $docs[$path] = filectime($path);
} arsort($docs); // sort by value, preserving keys

foreach ($docs as $path => $timestamp) {

// additional options
//    print date("d M. Y: ", $timestamp);
//    print '<a href="'. $path .'">'. basename($path) .'</a>' . " Size: " . filesize($path) .'<br />';

echo '<img src="'.$path.$file.'"/><br />'; 
}
?>


Previous answer

use the glob( ) function.

Making use of the glob() function, you can set the files and folder to your liking.

More on the glob( ) function on PHP.net

To display ALL files, use (glob("folder/*.*")

<?php

foreach (glob("images/*.jpg") as $file) { //change "images" to your folder
    if ($file != '.' || $file != '..') {
    
// display images one beside each other.
// echo '<img src="'.$dir.$file.'"/>';

// display images one underneath each other.
    echo '<img src="'.$dir.$file.'"/><br />'; 

    }
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top