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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.