How do I sort alphabetically with pictures in php?

economylol asked
php sorting arraylist
via

This is my array thing Basically right now I have a directory with 100,000 images. All are different names like d2jd29df.png fj329f.png etc. I want it to list them alphabetically on the webpage. Could someone give me a nudge in the right direction?

img 1 of code

img 2 of code


Answer
via

You need to read the entire directory into an array, then sort the array naturally (i.e., the way a human would) alphabetically. Finally, iterate each of the files and echo the filename for each of them.

<?php
$files  = array();
$dir    = '/path/to/images';
$handle = opendir($dir);

if ($handle) {
    while (false !== ($file = readdir($handle))) {
        if ($file !== '.' && $file !== '..') {
            $files[] = $file;
        }
    }
    closedir($handle);
}
sort($files, SORT_NATURAL);

foreach ($files as $file) {
    echo $file.'<br />';
}
Share This
Posted in: