Skip to content

Instantly share code, notes, and snippets.

@fmtarif
Created June 19, 2021 22:22
Show Gist options
  • Save fmtarif/e166f9ada6a5ed0617e34dfcca97f284 to your computer and use it in GitHub Desktop.
Save fmtarif/e166f9ada6a5ed0617e34dfcca97f284 to your computer and use it in GitHub Desktop.
#php generate unique random numbers within a range
<?php
//https://stackoverflow.com/a/24493651
function unique_randoms($min, $max, $count) {
$arr = array();
while(count($arr) < $count){
$tmp =mt_rand($min,$max);
if(!in_array($tmp, $arr)){
$arr[] = $tmp;
}
}
return $arr;
}
//https://stackoverflow.com/a/28154388
//avoids the use of in_array and doesn't generate a huge array.
//So, it is fast and preserves a lot of memory.
function getDistinctRandomNumbers ($nb, $min, $max) {
if ($max - $min + 1 < $nb)
return false; // or throw an exception
$res = array();
do {
$res[mt_rand($min, $max)] = 1;
} while (count($res) !== $nb);
return array_keys($res);
}
// return unique_randoms(20, 100, 20);
return getDistinctRandomNumbers(20, 20, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment