This article mainly introduces the PHP method for generating random numbers. It compares two different methods for generating random numbers and summarizes the techniques related to random numbers. For more information, see
This article mainly introduces the PHP method for generating random numbers. It compares two different methods for generating random numbers and summarizes the techniques related to random numbers. For more information, see
Generally, when we want to generate a random string, we always create a character pool first, and then generate a php random number using a loop and mt_rand () or rand, randomly select characters from the character pool, and finally piece together the required length.
The Code is as follows:
Function randomkeys ($ length)
{
$ Pattern = '1234567890abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLOMNOPQRSTUVWXYZ,./& l
T;> ?; #:@~ [] {}-_ = +) (* & ^ % ___ FCKpd __0 pound ;"! '; // Character pool
For ($ I = 0; $ I <$ length; $ I ++)
{
$ Key. = $ pattern {mt_rand ()}; // generate a php Random Number
}
Return $ key;
}
Echo randomkeys (8 );
This php random function can generate XC * = z ~ A string like 7L is random enough! Now we will introduce another method to generate random numbers using PHP: Use the chr () function to save the steps to create a character pool.
The Code is as follows:
Function randomkeys ($ length)
{
$ Output = '';
For ($ a = 0; $ a <$ length; $ a ++ ){
$ Output. = chr (mt_rand (33,126); // generate a php Random Number
}
Return $ output;
}
Echo randomkeys (8 );
In the second php random function, use mt_rand () to generate a php random number between 33 and 126, and then convert it into characters using the chr () function. View the ascii code table and you will find that 33 to 126 represents all the characters in the character pool of the first function. The second function has the same functionality as the first function, and is more concise.
I hope this article will help you with php programming.