Random numbers from a set?

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
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Random numbers from a set?

Post by spacebiscuit »

Hi,

Is it possible to generate a random number from a set.

For example I want to select 5 random number from 1 to 10 without an repetition.

Any help would be appreciated.

Thanks,

Rob.
User avatar
Gente
Forum Contributor
Posts: 252
Joined: Wed Jun 13, 2007 9:43 am
Location: Ukraine, Kharkov
Contact:

Post by Gente »

Pretty easy snippet :)

Code: Select all

$set = array();
while(count($set) < 5)
{
  $val = rand(1,10);
  if (!in_array($val, $set))
  {
    $set[] = $val;
  }
}
Dave2000
Forum Contributor
Posts: 126
Joined: Wed Jun 21, 2006 1:48 pm

Post by Dave2000 »

or...

Code: Select all

$nums = array_rand(range(1, 10), 5);
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Post by spacebiscuit »

Many thanks that works perfectly,

Rob.
Post Reply