Home > Backend Development > PHP Tutorial > PHP random number

PHP random number

巴扎黑
Release: 2023-03-01 09:52:01
Original
2106 people have browsed it

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


.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template