Page 1 of 1

Random Numbers [SOLVED]

Posted: Thu Jul 20, 2006 1:29 pm
by tecktalkcm0391
How can I get PHP to pick 5 random numbers, but where none of them are the same. I need numbers 1-75.

Posted: Thu Jul 20, 2006 1:32 pm
by RobertGonzalez

Posted: Thu Jul 20, 2006 1:35 pm
by daedalus__
this was seriously a rtfm

Posted: Thu Jul 20, 2006 1:37 pm
by John Cartwright
Untested.

Code: Select all

function getRandomNumbers($total, $min, $max)
{
   $randoms = array();

   while (count($randoms) < $total)
   {
      $seed = rand($min, $max);
  
      if (!in_array($seed, $randoms))
      {
         $randoms[] = $seed;
      }
   }

   return $randoms;
}

Posted: Thu Jul 20, 2006 1:38 pm
by John Cartwright
Daedalus- wrote:this was seriously a rtfm
I believe this is more of a case of generating unique random numbers, not generating the numbers themselves.

Posted: Thu Jul 20, 2006 1:43 pm
by Benjamin
This should give you 5 different random numbers.

Untested..

Code: Select all

<?php

function randomNum($length)
{
    $Rand = range(1,75);
    $num = '';

    for ($i = 0; $i < $length; $i++) {

        $counter = 0;
        
        while (true)
        {
            $x = rand(0,74);

            if (isset($Rand[$x]))
            {
                $num .= $Rand[$x];
                unset($Rand[$x]);
                break;
            }

            $counter++;

            if ($counter > 100)
            {
                return 'Error!';
            }
        }
        
    }

    return $num;
}

$RandomNumbers = randomNum(5);

?>
ya beat me to it Jcart

Posted: Thu Jul 20, 2006 1:45 pm
by RobertGonzalez
$error never gets set (does it?).

Posted: Thu Jul 20, 2006 1:46 pm
by Benjamin
Everah wrote:$error never gets set (does it?).
Fixed..

Posted: Thu Jul 20, 2006 2:01 pm
by tecktalkcm0391
WOW. THANKS EVERYONE! :D :D :D

Posted: Thu Jul 20, 2006 2:19 pm
by daedalus__
Jcart wrote:
Daedalus- wrote:this was seriously a rtfm
I believe this is more of a case of generating unique random numbers, not generating the numbers themselves.
ah, i see

Posted: Thu Jul 20, 2006 2:33 pm
by onion2k
Holy cow, you lot always overdo stuff..

Code: Select all

$a=range(1,75); //Make an array of numbers
shuffle($a); //Shuffle them to make them random
print_r(array_slice($a,0,5)); //Grab the first five

Posted: Thu Jul 20, 2006 2:36 pm
by Benjamin
Good job onion2k :)

Posted: Thu Jul 20, 2006 2:38 pm
by daedalus__
/agree
/clap

Posted: Thu Jul 20, 2006 10:20 pm
by RobertGonzalez
Onion, you make me cry with joy :cry: .

Posted: Fri Jul 21, 2006 3:14 am
by onion2k
Everah wrote:Onion, you make me cry with joy :cry: .
Aww. Hugs.