Page 1 of 1

Pick 3 random images from a list without duplicates

Posted: Mon Jul 11, 2005 8:38 am
by storkmarg
I have seen a few random image php scripts, but not one that does this:

1) I have a text file (images.txt) with

Code: Select all

<img src=&quote;a.gif&quote;>
<img src=&quote;b.gif&quote;>
<img src=&quote;c.gif&quote;>
<img src=&quote;d.gif&quote;>
<img src=&quote;e.gif&quote;>
etc.
2) I want to display n random lines from that file where none of the lines are the same. e.g. e, d and b but never b, c and b

The method I would normally use to do this would be to put each of the rows into an array and give each row a random number. I would then take the n biggest random numbers. My problem is that I don't know how to do this in php.

I also experience a problem with normal random row scripts which sometimes throw up nothing - counting the last row in the file as a line to pick from I suspect, so I would like this issue to be eliminated by only allowing rows containing text to be part of the array.

Does anyone know of a link to such a script?

Regards.

Posted: Mon Jul 11, 2005 8:58 am
by wwwapu
How about suffle() and then take n first images?

Code: Select all

$n=3;
$images=file('imagenames.txt');
suffle($images);
for($i=0; $i<$n; $i++){
  print $images[$i];
  //and possibly something else
}

Posted: Mon Jul 11, 2005 9:56 am
by pickle
An alternative way would be:

Code: Select all

$contents = file('imagenames.txt');
foreach(array_rand($contents,3) as $curr_image)
{
  echo $curr_image;
}
However, unlike using ~wwwapu's method, I'm not sure if this will ensure 3 different elements get picked.

Re: Pick 3 random images from a list without duplicates

Posted: Mon Jul 11, 2005 10:03 am
by wwwapu
storkmarg wrote:I also experience a problem with normal random row scripts which sometimes throw up nothing - counting the last row in the file as a line to pick from I suspect, so I would like this issue to be eliminated by only allowing rows containing text to be part of the array.
I didn't notice this before and now an idea came to me

Code: Select all

$n=3;
$images=file('imagenames.txt');
suffle($images);
for($i=0; $i<$n; $i++){
  if(!empty($images[$i]){
    print $images[$i];
  }else $n++;
}

Posted: Mon Jul 11, 2005 10:08 am
by storkmarg
Thanks guys...

The typo of shuffle threw me a bit to start, but it works great now. I never thought the code would be so simple. Thank you and thank you php.