Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Php random number of various knowledge collection


May 11, 2021 PHP


Table of contents


In the construction of website function, php random number is a common function, such as the user registration randomly generated verification code, and for example

Users can modify a random set of passwords when they register, and a random password is also required when the user needs to reset the password. R andom numbers are strings that are automatically generated according to a particular rule (or within an array range) and are widely used in php development, but random numbers in php are also divided into several different situations, so let's first look at the random number function rand() provided by PHP.


PhP's rand() function returns a random integer, as follows:

rand(min,max)

Optional parameters min and max enable Rand() to return pseudo-random RAND_MAX between 0 and 0. For example, if you want a random number between 5 and 15 (including 5 and 15), use rand (5, 15).



Let me look at a specific example, we make a basic function call, without setting specific parameters, we get random numbers will not be limited by min and max parameters.

echo(rand());?> 
Results: 652696728 (random results).

Php random number of various knowledge collection

Use PHP to generate random numbers within a specified interval

If we want to generate a random number between two numbers, we need to set two parameters for rand:

In this way, the result we get is in our control, and he should be MinNum and the result and MaxNum; assuming we're going to use PHP to generate random numbers between 1000 and 2000, our code should write this:
echo(rand(1000,2000));?> 
Simple enough, a little more difficult below. At the beginning of this article we said that random numbers are very useful, and we can solve some complex problems with PHP random numbers.

Use PHP to get random elements in a collection

Will set we need to get a random element from an array
$my_array=array('ASP','PHP','JAVASCRIPT','AJAX','CSS','JQUERY','HTML');  
echo($my_array[rand(0,6)]);   
?> 
As you can imagine, we might get any element in the array, such as ASP, PHP, or JavaScript. Note that our my_array array contains seven elements, and we set the rand() parameter to between 0 and 6.

Let's use two sets of random numbers to enhance the above example, we need one random number for conditional judgment, the other random number for the output of elements.
$my_array=array('ASP','PHP','JAVASCRIPT','AJAX','CSS','JQUERY','HTML');  
$repetition=rand(0,6);  
for($i=0;$i<=$repetition;$i++){  
echo('I am learning ' . $my_array[rand(0,6)]);  
echo(' on w3cschool.cn');  
}  
?> 
We may get results like this:

Php random number of various knowledge collection
The first run we got three results


Since we use a random number to limit the number of bars displayed, the result is that in addition to the article random, the number of bars displayed is also random, as shown in the following figure:

Php random number of various knowledge collection
The second run resulted in seven results

Next up are some other application methods for php random numbers.

PHP generates 32 random numbers

Using the token method, you can control the user's permissions during this time, as follows:
function genToken( $len = 32, $md5 = true ) {
       # Seed random number generator
          # Only needed for PHP versions prior to 4.2
          mt_srand( (double)microtime()*1000000 );
          # Array of characters, adjust as desired
          $chars = array(
              'Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`',
              'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.',
              '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a',
              'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')',
              '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n',
              '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T',
              'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*'
          );
          # Array indice friendly number of chars;
          $numChars = count($chars) - 1; $token = '';
          # Create random token at the specified length
          for ( $i=0; $i<$len; $i++ )
              $token .= $chars[ mt_rand(0, $numChars) ];
          # Should token be run through md5?
          if ( $md5 ) {
              # Number of 32 char chunks
              $chunks = ceil( strlen($token) / 32 ); $md5token = '';
              # Run each chunk through md5
              for ( $i=1; $i<=$chunks; $i++ )
                  $md5token .= md5( substr($token, $i * 32 - 32, 32) );
              # Trim the token
              $token = substr($md5token, 0, $len);
          } return $token;
      }

Php random number of various knowledge collection

Php generates N random numbers that are not repeated

Php's method of generating N random numbers that are not repeated:
It is necessary to generate 16 random numbers between 1-25 that are not repeated to fill.
Ideas:
By depositing random numbers into an array and removing duplicate values from the array, a certain number of non-repeating random numbers can be generated.

Example code:
<?php
  /*
  * array unique_rand( int $min, int $max, int $num )
  * 生成一定数量的不重复随机数
  * $min 和 $max: 指定随机数的范围
  * $num: 指定生成数量
  * site
  */
  function unique_rand($min, $max, $num{
  $count = 0;
  $return = array();
  while ($count < $num) {
  $return[] = mt_rand($min, $max);
  $return = array_flip(array_flip($return));
  $count = count($return);
  }
  shuffle($return);
  return $return;
  }
  $arr = unique_rand(1, 25, 16);
  sort($arr);
  $result = '';
  for($i=0; $i < count($arr);$i++)
  {
  $result .= $arr[$i].',';
  }
  $result = substr($result, 0, -1);
  echo $result;
  ?>
  运行结果:
  2,3,4,6,7,8,9,10,11,12,13,16,20,21,22,24

Description:
A random number is generated using mt_rand() function. This function generates random numbers four times faster than rand() on average.

The "flip method" is used to remove duplicate values in an array, which is to swap the key and value of the array twice with array_flip(). This is much faster array_unique using the "() ""
Before returning to the array, use shuffle() to give the array a new key name, guaranteeing that the key name is a continuous number of 0-n.
Failure to do so may result in a loss of key names when deleting duplicate values, which is not conducive to traversal.

Use php into n random numbers, requiring n numbers and equal to 100

$rand_array = array();
function  get_rand_n($rand_array) {
    $rand_number = mt_rand(1,9);
    if(empty($rand_array)) {
        $rand_array[] = $rand_number;
        return get_rand_n($rand_array);
    } else {
        $count = 0;
        foreach($rand_array as $item) {
            $count += $item;
        }
        if($count<100) {
            if($count+$rand_number == 100) {
                $rand_array[] = $rand_number;
                return $rand_array;
            } else if($count+$rand_number < 100) {
                $rand_array[] = $rand_number;
                return get_rand_n($rand_array); // 回掉再次计算
            } else { // 如果得到的值大于了100
                return get_rand_n($rand_array); // 重新获得随机数,知道为100的时候返回这个随机数数组
            }
        }
    }
}
$rand_array = get_rand_n($rand_array);
var_dump($rand_array);
Results:

Php random number of various knowledge collection

php gets a random number of four letters and numbers

We know that simple four-digit pure-digit authentication in php can be done with rand (1000,9999), but if we want random four-digit letters and numbers, how do we write functions? Here is a complete example.
<?php
function GetfourStr($len) 
{ 
  $chars_array = array( 
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", 
    "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", 
    "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", 
    "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", 
    "S", "T", "U", "V", "W", "X", "Y", "Z", 
  ); 
  $charsLen = count($chars_array) - 1; 
 
  $outputstr = ""; 
  for ($i=0; $i<$len; $i++) 
  { 
    $outputstr .= $chars_array[mt_rand(0, $charsLen)]; 
  } 
  return $outputstr; 
} 
echo GetfourStr(4);
?>
如果没有提供可选参数 min 和 max,mt_rand() 返回 0 到 RAND_MAX 之间的伪随机数。例如想要 0 到 46(包括 0 和 46)之间的随机数,用 mt_rand(0, 46)。	

Php random number of various knowledge collection

Php generates a random number of specified lengths

<?php   
  function get_random($len=3){  
  //range 是将10到99列成一个数组   
  $numbers = range (10,99);  
  //shuffle 将数组顺序随即打乱   
  shuffle ($numbers);   
  //取值起始位置随机  
  $start = mt_rand(1,10);  
  //取从指定定位置开始的若干数  
  $result = array_slice($numbers,$start,$len);   
  $random = "";  
  for ($i=0;$i<$len;$i++){   
     $random = $random.$result[$i];  
   }   
   return $random;  
 }  
  
//随机数  
function get_random2($length = 4) {  
    $min = pow(10 , ($length - 1));  
    $max = pow(10, $length) - 1;  
    return mt_rand($min, $max);  
}  
  
echo "<br/>";  
echo get_random(3);  
echo "<br/>";  
echo get_random2(6);  

Php generates three methods of random passwords

Method one:

1, in 33 - 126 to generate a random integer, such as 35,

2. Convert 35 to the corresponding ASCII code character

3, repeat the above 1, 2 steps n times, connect to the n-bit password

The algorithm mainly uses two functions, the mt_rand (int $min, int $max) function is used to generate random integers, where $min - $max is the asCII code range, here take 33 -126, you can adjust the range as needed, such as ASCII code table 97 - 122 bit corresponding to the English alphabet a - z, can refer to the ASCII code table; The chr (int $ascii) function is used to connect the corresponding $ascii Convert to a corresponding character.
function create_password($pw_length = 8)
{
$randpwd = '';
for ($i = 0; $i < $pw_length; $i++)
{
$randpwd .= chr(mt_rand(33, 126));
}
return $randpwd;
}
// 调用该函数,传递长度参数$pw_length = 6
echo create_password(6);

Method two:

1, preset a string $chars, including a -z, A-Z, 0-9, and some special characters

2, in $chars string randomly take a character

3, repeat the second step n times, you can get the length of n password
function generate_password( $length = 8 ) {
// 密码字符集,可任意添加你需要的字符
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
$password = '';
for ( $i = 0; $i < $length; $i++ )
{
// 这里提供两种字符获取方式
// 第一种是使用 substr 截取$chars中的任意一位字符;
// 第二种是取字符数组 $chars 的任意元素
// $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
return $password;
}

Method three:

1, preset an array of characters $chars, including a - z, A - Z, 0 - 9, as well as some special characters

2, through array_rand () from the array $chars randomly selected $length elements

3, according to the obtained key name array $keys, from the array $chars character stitching string. The disadvantage of this method is that the same characters are not taken repeatedly.
function make_password( $length = 8 )
{
// 密码字符集,可任意添加你需要的字符
$chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!',
'@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_',
'[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',',
'.', ';', ':', '/', '?', '|');
// 在 $chars 中随机取 $length 个数组元素键名
$keys = ($chars, $length);
$password = '';
for($i = 0; $i < $length; $i++)
{
// 将 $length 个数组元素连接成字符串
$password .= $chars[$keys[$i]];
}
return $password;
}

Time efficiency comparison

Using the following PHP code, we calculate the run time of the three random password generators above to generate 6-bit passwords, which in turn provides a simple comparison of their time efficiency.
<?php
function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
// 记录开始时间
$time_start = getmicrotime();
// 这里放要执行的PHP代码,如:
// echo create_password(6);
// 记录结束时间
$time_end = getmicrotime();
$time = $time_end - $time_start;
// 输出运行总时间
echo "执行时间 $time seconds";
?>

The end result is:

Method 1: 9.8943710327148E-5 seconds
Method 2: 9.6797943115234E-5 seconds
Method 3: 0.00017499923706055 seconds
You can see that method one and method two have similar execution times, while method three runs for a little longer.