Search code examples
phploopsfilesystemsdirscandir

Loop through scandir() in php in order


Trying to make a gallery and making it by creating a file tree and then getting PHP to loop through it. At first everything was in alphabetical order however now I added more into the gallery it went a bit random. Read somewhere that scandir() works by ordering the folders/files in the directory in alphabetical order and putting them into an array. What's the best way to loop through the array in alphabetical order still? Here is the existing code:

$newFiles = scandir("images/decks/", 1);

The original code used to loop through the directory using:

foreach (new DirectoryIterator('images/decks/') as $fileInfo) {

Solution

  • Your code will return an array containing files alphabetical in descending order. To get files sorted in ascending order, use this code:

       $newFiles = scandir("images/decks/", 0);
    

    Now, use foreach to iterate through returned file array.

       foreach($newFiles as $file)
       {
          //your code goes here
       }