Jump to content

random number


flemingmike

Recommended Posts

hello, i am trying to see how i can pick a random number between 1-15 and exclude certain numbers.

 

so i have a staff list that once a random number is created it inserts it into the staffnumber field.  so the next time i create a random number for a staff, i want to make sure that the random number doesnt select an existing staffnumber.

 

thanks!

Link to comment
https://forums.phpfreaks.com/topic/247681-random-number/
Share on other sites

This may not be the best way, but it works.

 

$max = 15;
$sql = mysql_query("select rand_num from staff");
$nums = array();
while($row = mysql_fetch_assoc($sql)){
     $nums[] = $row['rand_num'];
}
$staff_number = false;
if(count($nums) < $max){
     while(true){
          $num = mt_rand(1, 15);
          if(!in_array($nums)){
               $staff_number = $num;
               break;
          }
     }
}

var_dump($staff_number);

Link to comment
https://forums.phpfreaks.com/topic/247681-random-number/#findComment-1271905
Share on other sites

Why are you using a random number? You should be using an auto-incrementing ID field in the database. Then you do not need to specify the id it will be generated for you and you will ensure that there is never a duplicate.

 

But, on a purely academic basis, what you are asking is pretty simple. Use rande() to create an array from 1-15, then use chuffle() to randomize the array, then use array_pop() or array_shift() to get a value from the array and remove that value from the array. Then use that same function to get the next value and the next, until the array is empty.

 

$randomIDs = range(1, 15);
shuffle($randomIDs);

//Call this when you need an ID
$id = array_pop($randomIDs);

Link to comment
https://forums.phpfreaks.com/topic/247681-random-number/#findComment-1271934
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.