1

I want to display random n number of images from a folder. Currently i am using this script to display images

<?php
$dir = './images/gallery/';
foreach(glob($dir.'*.jpg') as $file) { ?>
<div class="item"><img src="<?php=$file;?>"></div>
<?php } ?>

I want only 10 (or n number) images, that too randomly. How to do this?

3 Answers 3

1

The shuffle() method will put the elements of a given array in a random order:

<?php
$dir = './images/gallery/';

function displayImgs($dir, $n=10){
$files = glob($dir.'*.jpg');
shuffle($files);
$files = array_slice($files, 0, $n);
foreach($files as $file) { ?>
<div class="item"><img src="<?php=$file;?>"></div>
<?php } 
} ?>

Usage: displayImgs("/dir/temp/path", 20);

Sign up to request clarification or add additional context in comments.

7 Comments

I am not sure if this is going to display random images
n is default equal to 10 in this function. If you have 10 images in an array then you will address them as 0 through 9 or (10-1) here
I know that @TravisConnelly , just ensuring Jitendra posts a well-rounded answer, not leaving much speculation from the OP ;-)
@JitendraKumar.Balla I am getting error Warning: array_slice() expects parameter 1 to be array, boolean given in...
@user3045457, Updated code, shuffle() will return boolean. so that is the small mistake.
|
1

Well, this might be overkill, but you can also use a directory iterator and some randomness to achieve this. I used a modified version of the random numbers generation function from this answer.

make sure that the path you give to the function is relative to the directory in which the script resides, with a slash at the beginning. The __DIR__ constants will not change would you happen to call this script from different places in your file hierarchy.

<?php

function randomImages($path,$n) {

    $dir = new DirectoryIterator(__DIR__. $path);

    // we need to know how many images we can range on
    // but we do not want the two special files . and ..
    $count = iterator_count($dir) - 2;

    // slightly modified function to create an array containing n random position
    // within our range
    $positionsArray = UniqueRandomNumbersWithinRange(0,$count-1,$n);

    $i = 0;
    foreach ($dir as $file) {

        // those super files seldom make good images
        if ($file->getFilename() === '.' || $file->getFilename() === '..') continue;

        if (isset($positionsArray[$i])) echo '<div class="item"><img src="'.$file->getPathname().'"></div>';

        $i++;
        // change the count after the check of the filename,
        // because otherwise you might overflow
    }
}

function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_flip(array_slice($numbers, 0, $quantity));
}

2 Comments

Super. Works fine. But, my inspect-element shows <img src="./images/gallery\images-room.jpg">. Why it shows \ instead /?
hmmm... not sure. you on a windows box? does it display correctly?
0

Let us first create a array and push some random numbers into it. And as per you let $n be 10.

$n = 10;
$arr = array();
for($i = 1; $i <= $n; $i++){
    /* Where $n is the limit */
    $rand = rand($n);
    array_push($arr, $rand);
}

So now we have an array containing the random digits and now we have to echo out the images by iterating over the array:

foreach($arr as $image){
    $intToStr = (string) $image;
    foreach(glob($dir. $intToStr . '.jpg') as $file){
        echo "<div class='item'>$file</div>";
    }
}

This would echo out your images.

1 Comment

Simply you can use shuffle()

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.