noon Posted June 16, 2008 Share Posted June 16, 2008 I need a function that accepts 1 parameter, $max. The function will return an array of numbers from 1 to $max (inclusive) in random order, with no repeats. Ex: echo rand_group(4); // 3,1,2,4 The only approach I can think of right now is generating the random, checking if its already in my array, add if not, generate again if it is. This brute force is quite inefficient I am sure. Wondering if anyone can help me write a better piece of code. For considerations, let's say the max number would never go above 10. Link to comment https://forums.phpfreaks.com/topic/110438-solved-simple-random-function/ Share on other sites More sharing options...
kenrbnsn Posted June 16, 2008 Share Posted June 16, 2008 Look at the range() and the shuffle() functions. <?php function rand_group($x) { $ary = range(1,$x); shuffle($ary); return($ary); } echo implode(', ',rand_group(4)); ?> Ken Link to comment https://forums.phpfreaks.com/topic/110438-solved-simple-random-function/#findComment-566609 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.