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

PHP batch randomly generates numbers without duplication

Release: 2023-02-27 22:28:01
Original
3736 people have browsed it

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;
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template