Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php 2000 unique random numbers between 1000 and 9999

I want to generate 2000 unique random numbers between range 1000 and 9999. I'm doing something like this but it is not generating unique numbers.

$numbers = array();             

// Loop while there aren't enough numbers
while (count($numbers) < 2000) {

    $random_number = rand(1000, 9999);

    if (!in_array($random_number, $numbers)) {             
       // This adds the number to the array      
       $numbers[] = 'A'.$random_number.'14';
    }

}

Please help.

like image 325
user3588408 Avatar asked Dec 03 '22 19:12

user3588408


1 Answers

Instead of running many random tries, for a small range such as this I'd rather use this approach:

$candidates = range(1000, 9999);
shuffle($candidates);
$numbers = array_slice($candidates, 0, 2000);
$numbers = array_map(function ($number) { return "A{$number}14"; }, $numbers);
like image 169
deceze Avatar answered Dec 05 '22 09:12

deceze