The most concise way to generate random numbers of specified length in PHP

coldplay.xixi
Release: 2023-04-09 11:02:02
forward
2830 people have browsed it

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);
}
Copy after login

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);
}
Copy after login

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!

Related labels:
source:jb51.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!