1
<?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 :)

  • 1
    as far as i know opendir will give you files in same order with ls -l so you can gather the files and then sort in php like [here](http://stackoverflow.com/questions/884974/sort-and-display-directory-list-alphabetically-using-opendir-in-php) – Santa's helper Sep 12 '14 at 14:02

2 Answers2

3

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
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
0

You may want to use

scandir()

php says it orders the files alphabeticaly take a look at: link

By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is set to SCANDIR_SORT_DESCENDING, then the sort order is alphabetical in descending order. If it is set to SCANDIR_SORT_NONE then the result is unsorted.

Santa's helper
  • 976
  • 8
  • 21