Home  >  Article  >  Backend Development  >  PHP batch randomly generates numbers without duplication

PHP batch randomly generates numbers without duplication

尚
Original
2019-10-29 13:44:173676browse

PHP batch randomly generates numbers without duplication

PHP random number batch generation:

Use the rand() function in PHP to generate random numbers, and then determine whether the random number already exists. If it does not exist, it will This random number is stored in an array. Repeat this method multiple times to generate random numbers in batches without repetition.

/**
 * 随机多个数字,可设定是否重复
 * @param int $min          
 * @param int $max          
 * @param int $num          
 * @param boolean $re           
 * @return array
 */
function randomNums($min, $max, $num, $re = false)
{
    $arr = array ();
    $t = 0;
    $i = 0;
    // 如果数字不可重复,防止无限死循环
    if (! $re)
    {
        $num = min($num, $max - $min + 1);
    }
    do
    {
        // 取随机数
        $t = mt_rand($min, $max);
        if (! $re && isset($arr[$t]))
        {
            // 数字重复
            continue;
        }
        $arr[$t] = $t;
        ++ $i;
    }
    while ($i < $num);
    return $arr;
}

Recommended: php server

The above is the detailed content of PHP batch randomly generates numbers without duplication. 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