Random Numbers [SOLVED]
Moderator: General Moderators
- tecktalkcm0391
- DevNet Resident
- Posts: 1030
- Joined: Fri May 26, 2006 9:25 am
- Location: Florida
Random Numbers [SOLVED]
How can I get PHP to pick 5 random numbers, but where none of them are the same. I need numbers 1-75.
Last edited by tecktalkcm0391 on Thu Jul 20, 2006 2:01 pm, edited 1 time in total.
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
- daedalus__
- DevNet Resident
- Posts: 1925
- Joined: Thu Feb 09, 2006 4:52 pm
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
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;
}
Last edited by John Cartwright on Thu Jul 20, 2006 1:51 pm, edited 1 time in total.
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
This should give you 5 different random numbers.
Untested..
ya beat me to it Jcart
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);
?>
Last edited by Benjamin on Thu Jul 20, 2006 1:46 pm, edited 2 times in total.
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
- tecktalkcm0391
- DevNet Resident
- Posts: 1030
- Joined: Fri May 26, 2006 9:25 am
- Location: Florida
- daedalus__
- DevNet Resident
- Posts: 1925
- Joined: Thu Feb 09, 2006 4:52 pm
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- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA