tags:

views:

120

answers:

2

Hi Everyone,

My name is Shruti.I'm new to php. I have a program which displays images randomly, there are about 200 images in my program.I want to display the random images with out repetition, can any one please help with this. here is my code.

Appreciate your help

Thank you.

+1  A: 

I don't know whats about the $img_id but you could consider to use shuffle().

shuffle($file_array);

But then you loose the connection to $img_id. You could (I am not sure if this is the best solution), build your array this way:

$file_array = array(
        array("images/bag200.bmp", 1),
        array("images/bag178.bmp", 1),
        array("images/bag004.bmp", 0,
        ...
);

In the long run, it is probably better to store all the image paths in a CSV file or even a database. Believe me, you don't want to maintain an array with > 200 entries manually ;)

You can loop over images this way (they are in random order now):

<?php foreach($file_array as $image): ?>
    <img src="<?php echo $image ?>" />
<?php endforeach; ?>

If you only want to display a subset of the images, randomly chosen, you can do this:

$n = 20; // want to display 20 images
$rand = array_rand(range(0,200), $n); // draw keys randomly

shuffle($rand); //shuffle keys

foreach($rand as $r) {
    echo '<img src="' . $file_array[$r] . '" />';
}

Some comments on your code:

$ran = array_rand($file_array);

$ran contains a key randomly chosen from the images.

for ($i=0;$i<200;$i++) {
    //while (in_array($tst,$rand_array)){
        $tst = $file_array[$ran];
        $id = $img_id[$ran];//}
    $rand_array[] = $tst;
    $rand_id[] = $id;
}

You always pick the same entry from $file_array and $image_id because you never change $ran. That is way you get the same image 200 times.

Felix Kling
$img_id is another array which is used for displaying the messages at the end of each image.... I have problem with randomizing the array...
Shruti
@Shruti: As you don't specify what exactly your problem is and for example if you want to display only some or all images, I provided various solutions. I hope it helps.
Felix Kling
@Kling thank you for your comments basically i'm generating a image slide show for 200 images with a gap of three seconds for each image all images should be randomized without any repetition.
Shruti
A: 

If you want randomness but require uniqueness, you are looking for a quasi-random number generator. There are many different types with different properties. Look here for information on creating an algorithm: http://www.mathworks.nl/access/helpdesk/help/toolbox/stats/br5k9hi-8.html

J Hall