0

I was wondering if it's possible to get a sequence of pictures into an array. I'd like to use JavaScript if possible, if not can it be possible with PHP and how?

So I created a map called "images/cars", which contains a lot of images. All the pictures have a different name. One is called: "audi", another one is called: "mercedes" and so on. They all are the same type (.gif).

I can do this manually like:

var pictures = ["audi.gif", "mercedes.gif", "aston martin.gif", ....]
// and so on

But that is too much work. Also, when I upload a new picture to the "images" folder, I have to manually add the new image to the array.

Here is my full code :

<!DOCTYPE html>
<html>
  <head>
    <script>
      var cars= ["audi.gif", "mercedes.gif", "aston martin.gif", "bmw.gif", "ferrari.gif"];
      var outputRandomImage = "";   

      function myFunction() {   
        for (var i = cars.length - 1; i >=0; i--) {
          var random = Math.floor(Math.random()*(i+1));
          var randomImage = cars[random];   
    
          cars[random] = cars[i]; 
          cars[i] = randomImage;
          outputRandomImage += '<img src="images/cars/' + randomImage + '">' + "<br>";
          document.getElementById("output").innerHTML = outputRandomImage;
        }   
      }
    </script>
  </head>
  <body onload="myFunction()">
    <p id="output"></p>
  </body>
</html>

Hope someone here could help. I'm open to any ideas, recommendations, and suggestions. Thank you.

1
  • Clearly you cannot get files on the server with Javascript, because it is ran in the browser after the server has served the html. However, you can use scandir() in PHP: php.net/manual/en/function.scandir.php and then use that to generate Javascript with an array in it. Commented May 14, 2017 at 7:53

1 Answer 1

1

One way is to create another PHP page

$folder = "."; // folder with the image files
$scan = scandir($folder);
$files = [];

foreach($scan as $file_name)
{
    if (!is_dir("$folder/$file_name"))
    {
        $array_push($files, $file_name) //  if it is not a directory add it to the files list
    }
}
$json_string = json_encode($ar);
echo $json_string;

And for the javascript

$.post("getCars.php", function(data, status){
    if(status==="success"){
        cars = JSON.parse(data)
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.