generate multiple unique random numbers

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!

Moderator: General Moderators

Post Reply
gth759k
Forum Commoner
Posts: 76
Joined: Mon Jun 15, 2009 3:04 am

generate multiple unique random numbers

Post by gth759k »

Ok, so I'm building a simple ad manager and what I want to do is generate say 3 random numbers between 1 and the number of rows in my mysql table. I know how to get the number of rows in my mysql table fine, I'm just not sure how to get 3 UNIQUE random numbers. Any help would be appreciated. Thanks.
gth759k
Forum Commoner
Posts: 76
Joined: Mon Jun 15, 2009 3:04 am

Re: generate multiple unique random numbers

Post by gth759k »

I think I came up with a simple solution.

$rand1 = rand(1, $adnum);
$rand2 = rand(1, $adnum);
$rand3 = rand(1, $adnum);

while ($rand1 == $rand2 || $rand1 == $rand3 || $rand2 == $rand1 || $rand2 == $rand3 || $rand3 == $rand1 || $rand3 == $rand2) {
$rand1 = rand(1, $adnum);
$rand2 = rand(1, $adnum);
$rand3 = rand(1, $adnum);
}

echo $rand1;
echo "<br>";
echo $rand2;
echo "<br>";
echo $rand3;
echo "<br>";
Post Reply