SoFunction
Updated on 2025-03-02

PHP generates N non-repetitive random number instances


<?php
/*
* array unique_rand( int $min, int $max, int $num )
* Generate a certain number of non-repetitive random numbers
* $min and $max: Specify the range of random numbers
* $num: Specify the number of generated
*/
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;
}

$arr = unique_rand(1, 25, 16);
sort($arr);

$result = '';
for($i=0; $i < count($arr);$i++)
{
 $result .= $arr[$i].',';
}
$result = substr($result, 0, -1);
echo $result;
?>