Random Numbers [SOLVED]
Posted: Thu Jul 20, 2006 1:29 pm
How can I get PHP to pick 5 random numbers, but where none of them are the same. I need numbers 1-75.
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
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;
}I believe this is more of a case of generating unique random numbers, not generating the numbers themselves.Daedalus- wrote:this was seriously a rtfm
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);
?>Fixed..Everah wrote:$error never gets set (does it?).
ah, i seeJcart wrote:I believe this is more of a case of generating unique random numbers, not generating the numbers themselves.Daedalus- wrote:this was seriously a rtfm
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 fiveAww. Hugs.Everah wrote:Onion, you make me cry with joy.