Page 1 of 1

Random numbers from a set?

Posted: Thu Jul 12, 2007 5:44 am
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.

Posted: Thu Jul 12, 2007 6:11 am
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;
  }
}

Posted: Thu Jul 12, 2007 6:42 am
by Dave2000
or...

Code: Select all

$nums = array_rand(range(1, 10), 5);

Posted: Thu Jul 12, 2007 8:43 am
by spacebiscuit
Many thanks that works perfectly,

Rob.