Home  >  Article  >  Backend Development  >  PHP random number

PHP random number

巴扎黑
巴扎黑Original
2016-11-30 09:26:442083browse

Normally, when we want to generate a random string, we always create a character pool first, then use a loop and mt_rand() or rand() to generate php random numbers, randomly select characters from the character pool, and finally piece it together Find the required length.

function randomkeys($length)
{
$pattern = '1234567890abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLOMNOPQRSTUVWXYZ,./&l
t;>?;#:@~[]{}-_=+)(*&^%___FCKpd___0pound ;" !'; //Character pool
for($i=0;$i<$length;$i++)
{
$key .= $pattern{mt_rand(0,35)}; //Generate PHP random numbers
}
return $key;
}
echo randomkeys(8); This PHP random function can generate strings like ) function, eliminating the step of creating a character pool. function randomkeys($length)
{
$output='';
for ($a = 0; $a < $length; $a++) {
$output .= chr(mt_rand(33, 126)); //Generate PHP random numbers
}
return $output;
}
echo randomkeys(8);

In the second PHP random function, first use mt_rand() to generate one PHP random numbers between 33 and 126 are then converted into characters using the chr() function. Looking at the ascii code table, you will find that 33 to 126 represent all the characters in the character pool in the first function. The second function has the same function as the first function, and is more concise


.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn