PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I have been trying to alter my code so that an image cannot be repeated twice. In my full code I have 200 images and each page has 30 include statements. It just some times a picture is repeated twice or even three times.
Does any one have any suggestions how i could get around this?
How often do you not want them to repeat? If it is every 200 times then just cycle through the list. You could save the current position in the session. Maybe you could start at a random image if the value in the session has not yet been set.
The way it works at the moment is i have a folder with 200 images. Each time the webpage is loaded the script gathers and displays 30 of them randomly.
Each time the page is refreshed a new random lot of 30 images appear.
The problem is i'm getting duplicate images appear.
Ideally when the page is refreshed i would like 30 individual images to appear with no duplicates. Thats what i cant figure out what to do.
What I would do is create a list of all images in the directory using scandir() then pick 30 random numbers, each time comparing them to a list of previous numbers, where each number is an index in the list.
$imgs=scandir("path/to/imgs/",1);//collect the imgs
$imgs=array_diff($imgs,array(".","..");//get rid of the dot filenames
$used=array();//the used random numbers
for($i=0;$i<30;$i++){//pick a random # 30 times
$r=rand(0,200); //pick the #
if(!in_array($r,$used)) //if it is not in the used #s:
$used[]=$r; //add it to the list
}
for($j=0;$j<count($used);$j++){ //loop through the 30 random numbers
$img=$imgs[$used[$j]];
// print the img tags
}
As for the original question, the birthday paradox would ensure that probability of repeated samples when picking 30 independent samples off a pool of 200 would be quite big.