0

I'm trying to get this php script which uses javascript to output images in alphabetical or numerical order by filename.

It's supposed to create an array with the images in a folder but for some reason the images are not in order. For example if I have four images named 1.jpg 2.jpg 3.jpg 4.jpg they display in the array in order BUT as soon as I add more than four it muddles the order. https://pastebin.com/3h9mmauC

<?
//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");

//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="images/") {
$pattern="(\.jpg$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
    while(false !== ($file = readdir($handle))){
        if(ereg($pattern, $file)){ //if this file is a valid image
            //Output it as a JavaScript array element
            echo 'galleryarray['.$curimage.']="'.$file .'";';
            $curimage++;
        }
    }

    closedir($handle);
}
return($files);
}

'var galleryarray=newArray();'; //Define array in JavaScript
 returnimages() //Output the array elements containing the image file names
 ?>
Laazo
  • 467
  • 8
  • 22
  • Possible duplicate of [PHP readdir() not returning files in alphabetical order](https://stackoverflow.com/questions/541510/php-readdir-not-returning-files-in-alphabetical-order) – olibiaz Jul 21 '17 at 14:50

1 Answers1

0

You could use Array.prototype.sort() to sort the JS Array. Like this:

echo 'var galleryarray=new Array();';
returnimages();
echo 'galleryarray.sort()';