Search code examples
phpopendir

php opendir file listing by number


<?php 
                if ($handle = opendir('img/albums/1/')) {
                    while (false !== ($file = readdir($handle))) { 
                        if ($file != "." && $file != "..") { 

                            echo "<li><div class='lay-outer pr db oh img_'><img src='img/albums/1/$file' class='open-img-sidebar-spec_' /></div></li>"; 

                        } 
                    }
                    closedir($handle); 
                }
            ?>

I have the following code. So, I am getting pictures from the certain derictory. All of the pictures in the derictory are listed from 1 to N number of them (ex. 1.jpg, 2.jpg and on).

I need to list them in order, so for example from 1 to 90 and so. Right now, they are listing randomly and I really want to fix it;

Please help, thank you :)


Solution

  • Considering they are numbered file names, you'll need a numerical or natural sorting versus alphabetical. So even another function like glob() wouldn't help.

    The naive solution would be:

    • loop over the files in the directory
    • store them in an array
    • sort the array using one of: sort($arr, SORT_NUMERIC), natsort(), etc.
    • loop over the array and output the files in order