flemingmike Posted September 23, 2011 Share Posted September 23, 2011 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! Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted September 23, 2011 Share Posted September 23, 2011 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); Quote Link to comment Share on other sites More sharing options...
Psycho Posted September 23, 2011 Share Posted September 23, 2011 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); Quote Link to comment Share on other sites More sharing options...
Nodral Posted September 23, 2011 Share Posted September 23, 2011 then use chuffle() to randomize the array, Now you're just making things up!!! lol Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.