cloudll Posted June 7, 2015 Share Posted June 7, 2015 Hey guys, I need 6 different random numbers for my script, so i'm using mt_rand with a range of 1 - 100. I was wondering if there was a way to make sure all 6 random numbers generated are different from each other? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/296694-having-6-random-numbers-output-different-numbers/ Share on other sites More sharing options...
Barand Posted June 7, 2015 Share Posted June 7, 2015 (edited) Array keys must be unique, so $rand_nums = []; while (count($rand_nums) < 6) { $rand_nums[mt_rand(1,100)] = 1; } The array keys will be your random numbers Edited June 7, 2015 by Barand Quote Link to comment https://forums.phpfreaks.com/topic/296694-having-6-random-numbers-output-different-numbers/#findComment-1513403 Share on other sites More sharing options...
cloudll Posted June 7, 2015 Author Share Posted June 7, 2015 Thanks thats working great, so would I then use extract() to turn the 6 outputs into variables? Quote Link to comment https://forums.phpfreaks.com/topic/296694-having-6-random-numbers-output-different-numbers/#findComment-1513406 Share on other sites More sharing options...
Barand Posted June 7, 2015 Share Posted June 7, 2015 Put them in an array $my_numbers = array_keys($rand_nums); Then your variables as $my_numbers[0], $my_numbers[1], ... , $my_numbers[5] Quote Link to comment https://forums.phpfreaks.com/topic/296694-having-6-random-numbers-output-different-numbers/#findComment-1513407 Share on other sites More sharing options...
requinix Posted June 7, 2015 Share Posted June 7, 2015 (edited) You can avoid a loop with $my_numbers = array_rand(array_flip(range(1, 100)), 6);or the cleaner $rand_nums = range(1, 100); shuffle($rand_nums); $my_numbers = array_slice($rand_nums, 0, 6);There won't be much of a difference if you're only getting 6 numbers out of 100, but if you tried more like 6/7 or 90/100 then you'd notice a big one. Edited June 7, 2015 by requinix Quote Link to comment https://forums.phpfreaks.com/topic/296694-having-6-random-numbers-output-different-numbers/#findComment-1513409 Share on other sites More sharing options...
cloudll Posted June 7, 2015 Author Share Posted June 7, 2015 Thanks guys, really helped me a lot Quote Link to comment https://forums.phpfreaks.com/topic/296694-having-6-random-numbers-output-different-numbers/#findComment-1513410 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.