Random numbers are useful for Web applications, WAP or mobile applications. I often need to deal with random numbers or random arrays in a few small projects recently. Therefore, I would like to summarize several common methods for generating non-repeated random numbers in PHP.
Random numbers are useful for Web applications, WAP or mobile applications. I often need to deal with random numbers or random arrays in a few small projects recently. Therefore, I would like to summarize several common methods for generating non-repeated random numbers in PHP.
Method 1:
$ Numbers = range (1, 50 );
// Shuffle will immediately disrupt the array order
Shuffle ($ numbers );
// Array_slice retrieves a segment of the array
$ Num = 6;
$ Result = array_slice ($ numbers, 0, $ num );
Print_r ($ result );
?>
Method 2:
$ Numbers = range (1, 20 );
// Broadcast the seed of the random number generator, which is dispensable and does not affect the test result.
Srand (float) microtime () * 1000000 );
Shuffle ($ numbers );
// Skip the first value of the list (the index is saved)
While (list (, $ number) = each ($ numbers )){
Echo "$ number ";
}
?>
Method 3:
Function NoRand ($ begin = 0, $ end = 20, $ limit = 5 ){
$ Rand_array = range ($ begin, $ end );
Shuffle ($ rand_array); // call the random array arrangement function.
Return array_slice ($ rand_array, 0, $ limit); // The first $ limit
}
Print_r (NoRand ());
?>
Five distinct values can be randomly generated between 1 and 20.
Method 4:
The code is as follows:
$ Tmp = array ();
While (count ($ tmp) <5 ){
$ Tmp [] = mt_rand (1, 20 );
$ Tmp = array_unique ($ tmp );
}
Print_r ($ tmp );
?>
Method 5:
The code is as follows:
$ Tmp = range (1, 30 );
Print_r (array_rand ($ tmp, 10 ));
?>
This may be simpler (ps: If the step is specified in the range, you must note whether the second parameter of array_rand exceeds the length of $ tmp ).