Generate array of different/unique random numbers in PHP

Sometime it is necessary to generate a list of different random numbers. A possible usage scenario therefore could be a raffle where the winners should be choosen by chance, but every single user shouldn’t get more than one prize.

So in the following snippet, I’ll show you how to generate a list of different randoms in PHP.

//Create an array of numbers from which the randoms
//should be choosen. (For raffle: the list of user id's)
$array = range($minimum, $maximum);

//Initialize the random generator
srand ((double)microtime()*1000000);

//A for-loop which selects every run a different random number
for($x = 0; $x < $numberOfRandoms; $x++)
     //Generate a random number
     $i = rand(1, count($array))-1;

     //Take the random number as index for the array
     $result[] = $array[$i];

     //The chosen number will be removed from the array
     //so it can't be taken another time
     array_splice($array, $i, 1);

Advice: $minimum, $maximum and $numberOfRandoms must be determined by you before.


  1. Hi,
    Here is a php function to get an array with unique random numbers.

    // Function to get an array with unique random numbers. Receives 3 arguments
    // $nri = number of items in array
    // $min = the lowest number
    // $max = the largest number
    function randomNrsArray($nri, $min, $max, $arr=array()) {
    // From:
    $nr = mt_rand($min, $max); // gets a random number

    // if the number already exists in $arr, autocalls this function
    // else, adds the number in $arr
    // if the number of items in $arr is lower then $nri, autocalls the function (till gets $nri elements in $arr)
    // returns the array
    if(in_array($nr, $arr)) $arr = randomNrsArray($nri, $min, $max, $arr);
    else {
    $arr[] = $nr;
    if(count($arr) < $nri) $arr = randomNrsArray($nri, $min, $max, $arr);
    return $arr;

    // Usage, gets an array with 5 uynique random numbers, between 1 and 100
    $nrs = randomNrsArray(5, 1, 100);

    // Test

    • Nice idea to get an backlink from me. But because you post brings a benefit for my readers I’ll gift you the link! ;)

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked