asmith Posted December 3, 2007 Share Posted December 3, 2007 hey guys how can i use rand finction to give me diffrent numbers each time ? never repeat a number twice ? i mean NOT like this : $a = rand(1,100) $b =rand(1,100) while ($a == $b) { $b = rand(1,100) } maybe this code is simple , but makes trouble when going for the 3rd number, what about the 20th number ?!! Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted December 3, 2007 Share Posted December 3, 2007 You need to store any previously generated random numbers in an array and check newly generated numbers against those stored. Something like: <?php $used = array(); $a = rand(1,100); $used[] = $a; $b = rand(1,100); while (in_array($b,$used)) $b = rand(1,100); $used[] = $b; ?> Note: not tested. Ken Quote Link to comment Share on other sites More sharing options...
asmith Posted December 3, 2007 Author Share Posted December 3, 2007 yea i guess it would work , if the rand range is (1,200) and we have 1 to 199 in $a array , would it takes time to rand and rand and rand till accidently find the number 200 ? if the the rand range go higher ,the last numbers wouldn't take so long to be found ? Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted December 3, 2007 Share Posted December 3, 2007 If you have known range of numbers, it is better to generate a list of all the numbers, randomize the list, and delete numbers as they get used. Quote Link to comment Share on other sites More sharing options...
asmith Posted December 3, 2007 Author Share Posted December 3, 2007 hmmm that means making an array with for exmaple 250 values ??? ! that take time ! if i get it wrong ,can you show me some example codes please? Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted December 3, 2007 Share Posted December 3, 2007 Depending on what you are going to use this for, you will need to store the un-used values in a flat-file or mysql database. To generate a range of values in an array, use the php range function - http://php.net/range Quote Link to comment Share on other sites More sharing options...
asmith Posted December 3, 2007 Author Share Posted December 3, 2007 hmm ok ! i thought this "no-repeating" rand is so simple that could have an individual function ! never thought of this much trouble ! 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.