Home  >  Article  >  Backend Development  >  PHP code that generates a certain number of non-repeating random numbers

PHP code that generates a certain number of non-repeating random numbers

WBOY
WBOYOriginal
2016-07-25 08:45:14869browse
Generate a certain number of unique random numbers
  1. /*
  2. * array unique_rand( int $min, int $max, int $num )
  3. * Generate a certain number of unique random numbers
  4. * $min and $max: Specify the range of random numbers
  5. * $num: Specify the generated number
  6. */
  7. function unique_rand($min, $max, $num) {
  8. $count = 0;
  9. $return = array();
  10. while ($count < $num) {
  11. $return[] = mt_rand($min, $max);
  12. $return = array_flip(array_flip($return));
  13. $count = count($return);
  14. }
  15. shuffle($return);
  16. return $return;
  17. }
  18. $arr = unique_rand(1, 25, 16);
  19. sort($arr);
  20. $result = '';
  21. for($i=0; $i < count($arr);$i++)
  22. {
  23. $result .= $arr[$i].',';
  24. }
  25. $result = substr($result, 0, -1);
  26. echo $result;
  27. ?>
Copy code

PHP


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn