Random #'s with a twist

I’m venturing away from my ASP comfort zone to write what, on the surface, seems like a fairly simple script in PHP.

I have a small table that is a single row of 5 thumbnail images showing featured products. I want to select these five items at random from a specified list of items. Sounds easy enough, just generate five random numbers. BUT, how do I go about making sure that I have no duplicates?

Perplexed in Texas :puzzle:

OK, I found a solution. It’s not particularly pretty, but it works. It probably would have come easier if I didn’t have to concentrate so much at this point just on PHP syntax. ASP habits are hard to break. :}


<?
// Initialize
$seed = (float) microtime() * 100000000;
srand($seed);

$numitems = 12;

$var1 = rand(1,$numitems);

$not_unique = true;
While ($not_unique)
{
  $var2 = rand(1,$numitems);
  if ($var2 != $var1)
    $not_unique = false;
}

$not_unique = true;
While ($not_unique)
{
  $var3 = rand(1,$numitems);
  if (($var3 != $var2) AND ($var3 != $var1))
    $not_unique = false;
}

$not_unique = true;
While ($not_unique)
{
  $var4 = rand(1,$numitems);
  if (($var4 != $var3) AND ($var4 != $var2) AND ($var4 != $var1))
    $not_unique = false;
}

$not_unique = true;
While ($not_unique)
{
  $var5 = rand(1,$numitems);
  if (($var5 != $var4) AND ($var5 != $var3) AND ($var5 != $var2) AND ($var5 != $var1))
    $not_unique = false;
}
?>

<?

$ar = array(1,2,3,4,5,6,7,8,9,10,11,12);

$keys = array_rand($ar, 5);

for($x=0;$x<count($keys);$x++){
    print $ar[$keys[$x]] . "<br />";
}

?>

that works as well…

sorry for the delay. :slight_smile:

Ah, now that’s much prettier code. :}

I need to spend some more time learning to use those array functions.

Thanks :cap:

Nice Vash… After reading what he said… I came up with the same conclusion in my head…

Yes ab, the array functions are incredibly nice in PHP. :slight_smile:

No problem. If you ever need any help just post away or send a PM. I don’t check the forums nearly as often as I used to but I still hit them up once a day or so. :slight_smile: always happy to help…

Playa: Yeah, I think thats the best (fastest ;)) way to go about getting the unique values… what can I say… “Great minds think alike” and sometimes you think like me… :stuck_out_tongue:


[size=1]random numbers doin’ the twist[/size]

Rev

Wow, that’s one hot number you got there rev :wink:

I thought she was fairly random

Rev