purplenewt Posted October 6, 2008 Share Posted October 6, 2008 Hi I am a bit new to php and have run into a problem, I need to generate a random number list on request from a user. eg, user selects 20 so I would need to have 20 unique random numbers from a range of 1-500. I tried to work things out and eventually after much trial and error, searching and deleting I found this here which is using random range and shuffle. Unfortunately this gives me 500 unique random numbers instead of 20 as I had hoped. <?php function rand_group() { $ary = range(1,500); shuffle($ary); return($ary); } echo implode(', ',rand_group(20)); ?> Any help would be great, this seems so close to what I need so I am thinking I am missing something really simple. Purplenewt Link to comment https://forums.phpfreaks.com/topic/127259-solved-random-numbers-within-a-certain-range-that-do-not-repeat/ Share on other sites More sharing options...
genericnumber1 Posted October 6, 2008 Share Posted October 6, 2008 The problem with your implementation is that it uses a lot of memory. That said, you were close... function rand_group($num) { $ary = range(1,500); shuffle($ary); return array_slice($ary, 0, $num); } echo implode(', ',rand_group(20)); EDIT: If you're going to be using large numbers (near 500) your implementation may be best, but if you're going to stick with small numbers (near 20) it would be more memory efficient (though slower) to do.. function rand_group($num) { $array = array(); while(count($array) < $num) { $randNum = rand(1,500); $array[$randNum] = $randNum; } return $array; } echo implode(', ', rand_group(20)); Link to comment https://forums.phpfreaks.com/topic/127259-solved-random-numbers-within-a-certain-range-that-do-not-repeat/#findComment-658189 Share on other sites More sharing options...
purplenewt Posted October 6, 2008 Author Share Posted October 6, 2008 Excellent thats perfect, thanks a ton. Purplenewt Link to comment https://forums.phpfreaks.com/topic/127259-solved-random-numbers-within-a-certain-range-that-do-not-repeat/#findComment-658193 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.