This article mainly introduces four methods for generating non-repeated random numbers and arrays in php. This article provides the implementation code and compares the generation efficiency, you can refer to the following methods to generate random numbers that are not repeated.
The code is as follows:
<? Php
Define ('random _ MAX ', 100 );
Define ('count', 10 );
Echo 'Max random num: '. RANDOM_MAX,'; result count: '. COUNT ,'
';
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'
';
}
Function rand1 (){
$ Numbers = range (1, RANDOM_MAX );
Shuffle ($ numbers); // randomly breaks the array
$ 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 faster random function than rand ()
$ Result = array_unique ($ result); // delete repeated elements in the array
}
Return $ result;
}
Function rand3 (){
$ Result = array ();
While (count ($ result) <COUNT ){
$ _ Tmp = mt_rand (1, RANDOM_MAX );
If (! In_array ($ _ tmp, $ result) {// Insert is allowed only when the same element does not exist in the array.
$ Result [] = $ _ tmp;
}
}
Return $ result;
}
Function rand4 (){
$ Result = array ();
While (count ($ result) <COUNT ){
$ Result [] = mt_rand (1, RANDOM_MAX );
$ Result = array_flip ($ result); // array_flip exchanges the key and value of the array.
}
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 method is the flip method. array_flip () is used to flip the keys and values of the array. using the php array feature, duplicate keys will overwrite and then flip again, it is the same as removing duplicate values.
The above methods are just simple examples, and some methods have limited applicability.
Let's take a look at the efficiency of several methods:
When array_unique () is used, the performance is poor when the array is large. of course, shuffle () will also be affected.