Home > Article > Backend Development > Two ways to generate random numbers in PHP
This article mainly introduces two methods of randomly generating numbers in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.
The first method uses mt_rand():
function GetRandStr($length){ $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $len=strlen($str)-1; $randstr=''; for($i=0;$i<$length;$i++){ $num=mt_rand(0,$len); $randstr .= $str[$num]; } return $randstr; } $number=GetRandStr(6); echo $number;
The second method (fastest)
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 = array_rand($chars, $length); $password = ''; for($i = 0; $i < $length; $i++) { // 将 $length 个数组元素连接成字符串 $password .= $chars[$keys[$i]]; } return $password; }
Related recommendations:
Detailed explanation of JS randomly generated numbers and sequence methods
Instance of using ip proxy pool to randomly generate IP in python3 requests
Randomly generated addition and subtraction algorithm method Verification code
The above is the detailed content of Two ways to generate random numbers in PHP. For more information, please follow other related articles on the PHP Chinese website!