PHP Simplest Method for Generating Random Numbers of Specified Length
- 2021-07-07 06:40:41
- OfStack
Just now, I was writing the SMS verification code module, and I needed to use random numbers with specified digits. Then I found that it was terrible to find such a simple thing on the Internet. I actually used several 10 lines of multiple loops nested... It seems that it is really unsuitable to be a programmer without a good brain.
I wrote a 1-line version:
function generate_code($length = 4) {
return rand(pow(10,($length-1)), pow(10,$length)-1);
}
In order to facilitate understanding, but also for this hydrology can gather some words, this is a multi-line version:
function generate_code($length = 4) {
$min = pow(10 , ($length - 1));
$max = pow(10, $length) - 1;
return rand($min, $max);
}