Home >Backend Development >PHP Tutorial >Several ways to generate random numbers in PHP
The following method is what I often use, it is more user-friendly
/** * 生成随机字符串 * @param int $length 要生成的随机字符串长度 * @param string $type 随机码类型:0,数字+大写字母;1,数字;2,小写字母;3,大写字母;4,特殊字符;-1,数字+大小写字母+特殊字符 * @return string */ function randCode($length = 5, $type = 0) { $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|"); if ($type == 0) { array_pop($arr); $string = implode("", $arr); } else if ($type == "-1") { $string = implode("", $arr); } else { $string = $arr[$type]; } $count = strlen($string) - 1; for ($i = 0; $i < $length; $i++) { $str[$i] = $string[rand(0, $count)]; $code .= $str[$i]; } return $code; }
Generate fixed-length random numbers:
function generate_code($length = 4) { return rand(pow(10,($length-1)), pow(10,$length)-1); }
The following has the same effect as the above, but the writing method is different.
function generate_code($length = 4) { $min = pow(10 , ($length - 1)); $max = pow(10, $length) - 1; return rand($min, $max); }
For example:
echo generate_code(5); //输出结果: 56482
Refresh again, so the numbers and order will change.
The above two codes are relatively simple, but they can only generate numbers. Those who pursue code simplicity can use
$arr=range(1,10); shuffle($arr); foreach($arr as $values) { echo $values.","; } //输出结果:10,5,7,8,6,2,9,4,1,3,1
This is mainly generated by PHP's built-in function range(), which generates random numbers in two parameter ranges. And they can generate multiple sets of numbers, which is more rigid, and not all of them are placed in the method, but you can use them according to your needs.
The following one is not much different from the above one, but the generation method is different, mainly generated by the array_unique function.
$arr=array(); while(count($arr)<10) { $arr[]=rand(1,10); $arr=array_unique($arr); } echo implode(" ",$arr);
I won’t go into details about other generation methods here. We just need to remember the commonly used and more efficient ones. During the development process, we can write our own PHP according to our needs. Random number function.