Gunjan Patel
Gunjan Patel

Reputation: 2372

why php rand() function gives some time empty?

Hello When I try to use rand() function than it's give sometime empty like

// I want random value between 0-5000 , want 500 random value
 for ($i=0; $i < 500; $i++) { 
    $randNo = rand(0, 5000);

    if (in_array($randNo, $randArray)) {
        $randNo = InfiniteLoop($randArray ,$length_sec);
    }
    array_push($randArray,$randNo);
}
sort($randArray);

After that i print that array give some empty value.

//output
Array ( [0] =>  [1] => 523 [2] => 824 [3] ....so on )

Upvotes: 0

Views: 168

Answers (3)

I&#39;m Geeker
I&#39;m Geeker

Reputation: 4637

Use :

$allNumbers = [];

for ($i = 0; $i < 5000; $i++) {
    $allNumbers[] = $i;
}

uniqid($allNumbers);

Upvotes: 0

Phylogenesis
Phylogenesis

Reputation: 7880

If you want 500 distinct random numbers between 0 and 5000, then you should probably use shuffle() and array_slice():

$allNumbers = range(0, 5000);

shuffle($allNumbers);

$randomNumbers = array_slice($allNumbers, 0, 500);

Upvotes: 2

Luthando Ntsekwa
Luthando Ntsekwa

Reputation: 4218

The problem might be your 'InfiniteLoop' function, it is overwritting the results of rand()

Upvotes: 0

Related Questions