Home > Article > Backend Development > The most concise way to generate random numbers of specified length in PHP
I was writing a SMS verification code module just now. I needed to use a random number with a specified number of digits. Then I searched online and found that it was terrible that such a simple thing actually took dozens of lines. A nested loop... It seems that those without a good brain are really not suitable to be programmers.
I wrote a one-line version:
function generate_code($length = 4) { return rand(pow(10,($length-1)), pow(10,$length)-1); }
In order to facilitate understanding, and also to collect some words for this hydrology, 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); }
Related learning recommendations: PHP programming from entry to proficiency
The above is the detailed content of The most concise way to generate random numbers of specified length in PHP. For more information, please follow other related articles on the PHP Chinese website!