Alexander Teshabaev
Alexander Teshabaev

Reputation: 100

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

Upvotes: 1

Views: 94

Answers (2)

Santa&#39;s helper
Santa&#39;s helper

Reputation: 996

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.

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 73021

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

Upvotes: 3

Related Questions