PHP for image randomization

I upload a folder full of images to create a jQuery image gallery.

Currently 100 images are being uploaded to create the gallery. I have everything to download without problems.

All I want to do is make uploaded images, upload in random order.

How do I achieve this?

My code is:

<?php
            $folder = "images/";
            $handle = opendir($folder);  
            while(($file = readdir($handle)) !== false)  {    
              if($file != "." && $file != "..")
              {      
                echo ("<img src=\"".$folder.$file."\">");
              }
}
?>

Thanks in advance.

+3
source share
3 answers

You can try something like this:

<?php
    $folder = "images/";
    $handle = opendir($folder);  
    $picturesPathArray;
    while(($file = readdir($handle)) !== false)  {    
        if($file != "." && $file != "..")
            $picturesPathArray[] = $folder.$file; 
    }
    shuffle($picturesPathArray);   


    foreach($picturesPathArray as $path) {  
        echo ("<img src=\"".$path."\">");
     }

?>
+4
source

Just save all the image paths in an array and randomly shuffle the array. And then the echo elements

<?php
            $folder = "images/";
            $handle = opendir($folder);
            $imageArr = array();  
            while(($file = readdir($handle)) !== false)  {    
              if($file != "." && $file != "..")
              {   
                $imageArr[] =    $file;               
              }
            shuffle($imageArr);  // this will randomly shuffle the image paths
            foreach($imageArr as $img)  // now echo the image tags
             {
                echo ("<img src=\"".$folder.$img."\">");
             } 
}
?>
+8
source

Go to the directory and save the image file names to an array and randomly select the path names from the array.

Basic example:

$dir = new DirectoryIterator($path_to_images);
$files = array();

foreach($dir as $file) {
    if (!$fileinfo->isDot()) {
        $files[] = $file->getPathname();
    }
}//$files now stores the paths to the images. 
+6
source

Source: https://habr.com/ru/post/1794429/


All Articles