user1698200
user1698200

Reputation: 1

how to load images from a directory in a sequence with php?

I have this php code that works great, but the only thing is that images that are loaded from the folder are random, and I need them to load numerically by order.

`

//Open images directory
$dir = opendir("../blogimg/luda_jesus");


//List files in images directoryb
while (($file = readdir($dir)) !== false)
  {
      if(substr( $file, -3 ) == "jpg" )

      {
        echo "<div class='container'><img class='lazy' id='background'  src='../blogimg/loader.gif' data-original='../blogimg/luda_jesus/" . $file . "' width='884' height='587'></div>";

        //echo "<br />";

      }
  }

closedir($dir);

?>` 

Please help me

Upvotes: 0

Views: 5597

Answers (2)

Nick Andriopoulos
Nick Andriopoulos

Reputation: 10643

Assuming "numerically" means by filename, you can simply do you while loop and populate all files in an array, sort it, and then load the files.

Example:

//Open images directory
$dir = opendir("../blogimg/luda_jesus");

//List files in images directoryb
while (($file = readdir($dir)) !== false) {
   if(substr( $file, -3 ) == "jpg" ) { 
     $filelist[] = $file;
   }
}

closedir($dir);
sort($filelist);

for($i=0; $i<count($filelist)-1; $i++) {
  echo "<div class='container'>
    <img class='lazy' id='background'  
      src='../blogimg/loader.gif' 
      data-original='../blogimg/luda_jesus/" . $file . "' 
      width='884' height='587'>
   </div>";
}

If you require different means of sorting, please mention so.

Upvotes: 0

Jon
Jon

Reputation: 437366

You can do this much more easily with glob:

$files = glob("../blogimg/luda_jesus/*.jpg");
natsort($files); // can also use other sort functions here, take your pick
foreach ($files as $file) {
    echo '...';
}

I chose natsort as the sort function above because it will sort 2.jpg before 10.jpg, while plain sort will do the opposite. See comparison of array sorting functions for more information.

Upvotes: 1

Related Questions