jagoan-neon Posted July 10, 2008 Share Posted July 10, 2008 Hello Masters, I need a little help. this is my code <? $array = array(0,1,2,3,4,5,6,7,8,9,10); $rand = mt_rand(0,10); for ($i = 0; $i < 8; $i++) { echo $array[$rand]." "; $rand = mt_rand(0,10); } ?> The result will always random, here is my result : 2 3 1 4 5 5 2 8 The question is : How to make a unique result for each number, I do not want the same number show up again like number 2 and 5. I want to have this result : 0 8 4 9 6 5 7 3 or 7 6 4 8 5 10 1 0 or 4 9 7 10 3 2 0 5 (random number but each one is unique doesn't appear twice or more) How to do it? Thank you. Link to comment https://forums.phpfreaks.com/topic/114049-solved-how-to-generate-unique-number/ Share on other sites More sharing options...
ratcateme Posted July 10, 2008 Share Posted July 10, 2008 the best way i have found on how to do this is to put the generated numbers in an array <?php $rand = array(); for ($i = 0; $i < 8; $i++) { $number = mt_rand(0,10); while(array_search($number,$rand)===false){ $number = mt_rand(0,10); } echo $number . " "; } ?> Scott. Link to comment https://forums.phpfreaks.com/topic/114049-solved-how-to-generate-unique-number/#findComment-586198 Share on other sites More sharing options...
jagoan-neon Posted July 10, 2008 Author Share Posted July 10, 2008 Thanks for the reply, but it's still not working <? $rand = array(0,1,2,3,4,5,6,7,8,9,10); for ($i = 0; $i < 8; $i++) { $number = mt_rand(0,10); while(array_search($number,$rand)===false){ $number = mt_rand(0,10); } echo $number . " "; } ?> The results : 2 8 1 5 1 4 8 1 - 1rst 2 10 5 4 5 4 5 5 - 2nd 8 10 5 8 8 5 0 2 - 3th Still, no unique number in each result Link to comment https://forums.phpfreaks.com/topic/114049-solved-how-to-generate-unique-number/#findComment-586204 Share on other sites More sharing options...
thebadbad Posted July 10, 2008 Share Posted July 10, 2008 shuffle() should be helpful: <?php $n = range(0, 10); shuffle($n); echo implode(' ', array_slice($n, 3)); ?> Link to comment https://forums.phpfreaks.com/topic/114049-solved-how-to-generate-unique-number/#findComment-586222 Share on other sites More sharing options...
kenrbnsn Posted July 10, 2008 Share Posted July 10, 2008 Use the shuffle() function: <?php $rand = range(0,10); shuffle($rand); echo implode(' ',array_slice($rand,0,); ?> Ken (Beaten to it -- GMTA) Link to comment https://forums.phpfreaks.com/topic/114049-solved-how-to-generate-unique-number/#findComment-586226 Share on other sites More sharing options...
jagoan-neon Posted July 10, 2008 Author Share Posted July 10, 2008 Thanks! PHPFreaks is the BEST! Link to comment https://forums.phpfreaks.com/topic/114049-solved-how-to-generate-unique-number/#findComment-586229 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.