sacox Posted January 9, 2010 Share Posted January 9, 2010 I want to get 3 unique random number out of 10 But I couldn't get the result with this script: <?php print(mt_rand(1,10));print("<br />"); print(mt_rand(1,10));print("<br />"); print(mt_rand(1,10));print("<br />"); ?> This script sometimes produce duplicate number Link to comment https://forums.phpfreaks.com/topic/187803-how-to-get-3-unique-random-number-out-of-10/ Share on other sites More sharing options...
The Little Guy Posted January 9, 2010 Share Posted January 9, 2010 You could do it like this: $arr = array(); while(true){ $rand = mt_rand(1, 10); if(!in_array($rand, $arr)){ $arr[] = $rand; } if(count($arr) == 3){ break; } } print_r($arr); Link to comment https://forums.phpfreaks.com/topic/187803-how-to-get-3-unique-random-number-out-of-10/#findComment-991580 Share on other sites More sharing options...
ignace Posted January 9, 2010 Share Posted January 9, 2010 Or $array = range(0, 10); $keys = array_rand($array, 3); echo $array[$keys[0]]; echo $array[$keys[1]]; echo $array[$keys[2]]; I'm not sure these are unique. Link to comment https://forums.phpfreaks.com/topic/187803-how-to-get-3-unique-random-number-out-of-10/#findComment-991659 Share on other sites More sharing options...
salathe Posted January 9, 2010 Share Posted January 9, 2010 I'm not sure these are unique. The same key will not be returned more than once from array_rand: so yes, in that case they would be unique. Link to comment https://forums.phpfreaks.com/topic/187803-how-to-get-3-unique-random-number-out-of-10/#findComment-991666 Share on other sites More sharing options...
ignace Posted January 9, 2010 Share Posted January 9, 2010 Ok thanks salathe already thought they would. Not sure, manual does not tell explicitly. And congrats with your recent promotion. Link to comment https://forums.phpfreaks.com/topic/187803-how-to-get-3-unique-random-number-out-of-10/#findComment-991687 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.