Here are several ways to generate a random number, directly on the code
Copy Code code as follows:
<?php
Define (' Random_max ', 100);
Define (' COUNT ', 10);
echo ' Max random num: '. Random_max, '; Result Count: '. COUNT, ' <br/> ';
Invoke_entry (' Rand1 ');
Invoke_entry (' Rand2 ');
Invoke_entry (' Rand3 ');
Invoke_entry (' Rand4 ');
function Invoke_entry ($func _name) {
$time = new Time ();
$time->time_start ();
Call_user_func ($func _name);
echo $func _name. ' Time spend: ', $time->time_spend ();
Echo ' <br/> ';
}
function Rand1 () {
$numbers = Range (1, Random_max);
Shuffle ($numbers); Randomly scrambling arrays
$result = Array_slice ($numbers, 1, COUNT);
return $result;
}
function Rand2 () {
$result = Array ();
while (count ($result) < count) {
$result [] = Mt_rand (1, Random_max); Mt_rand () is a better and faster random function than rand ()
$result = Array_unique ($result); To delete a duplicate element in an array
}
return $result;
}
function Rand3 () {
$result = Array ();
while (count ($result) < count) {
$_tmp = Mt_rand (1, Random_max);
if (!in_array ($_tmp, $result)) {//when the same element does not exist in the array, the insertion is allowed
$result [] = $_tmp;
}
}
return $result;
}
function Rand4 () {
$result = Array ();
while (count ($result) < count) {
$result [] = Mt_rand (1, Random_max);
$result = Array_flip (Array_flip ($result)); Array_flip the key and value of the array to Exchange
}
return $result;
}
Class Time {
Private $_start;
Public Function Time_start () {
$this->_start = $this->microtime_float ();
}
Public Function Time_spend () {
return $this->microtime_float ()-$this->_start;
}
Private Function Microtime_float () {
List ($usec, $sec) = Explode ("", Microtime ());
Return ((float) $usec + (float) $sec);
}
}
?>
The fourth way, is to turn the method, using Array_flip () to the array of keys and values flip, using the PHP array features, repeated keys will be overwritten, and then flip again, the same as the removal of duplicate values.
These methods are simple examples, and some methods are limited in scope.
Look at the efficiency of several methods:
With Array_unique () The performance is poor when the array is large, and of course shuffle () is also affected by this.