Home  >  Article  >  Backend Development  >  How to generate unique numbers within a specified range in php

How to generate unique numbers within a specified range in php

王林
王林Original
2020-07-23 15:58:092367browse

php method to generate unique numbers within a specified range: first generate random numbers through the mt_rand() function; then remove duplicate numbers through the array_flip() function. The array_flip() function is used to reverse the key names in the array and the corresponding associated key values.

How to generate unique numbers within a specified range in php

Function introduction:

(Recommended tutorial: php tutorial)

mt_rand() function Generate random integers using the Mersenne Twister algorithm. A random integer between min (or 0) and max (or mt_getrandmax()), inclusive. If max < min returns FALSE.​

Tip: This function is a better choice for generating random values, returning results 4 times faster than the rand() function.

array_flip() function is used to reverse/exchange the key names in the array and the corresponding associated key values. If the reversal is successful, the reversed array is returned. If the reversal fails, NULL is returned.

Code implementation:

<?php
/*
* array unique_rand( int $min, int $max, int $num )
* 生成一定数量的不重复随机数,指定的范围内整数的数量必须
* 比要生成的随机数数量大
* $min 和 $max: 指定随机数的范围
* $num: 指定生成数量
*/
function unique_rand($min, $max, $num) {
  $count = 0;
  $return = array();
  while ($count < $num) {
    $return[] = mt_rand($min, $max);
    $return = array_flip(array_flip($return));
    $count = count($return);
  }
  //打乱数组,重新赋予数组新的下标
  shuffle($return);
  return $return;
}

//生成10个1到100范围内的不重复随机数
$arr = unique_rand(1, 100, 10);
echo implode($arr, ",");
?>

Program running result:

48,5,19,36,63,72,82,77,46,16

The above is the detailed content of How to generate unique numbers within a specified range in php. For more information, please follow other related articles on the PHP Chinese website!

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