Home > Article > Backend Development > PHP random number
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