剛才在寫短信驗證碼模塊,需要用到指定位數的隨機數,然后網上一找發現太可怕了這么簡單的事情竟然用了好幾十行多個循環嵌套……看來沒有好腦仁兒真的不適合當程序員。
自寫了一行版本:
1
2
3
|
function generate_code( $length = 4) { return rand(pow(10,( $length -1)), pow(10, $length )-1); } |
為了便于理解,同時也為了這篇水文可以湊點字數,這是多行版:
1
2
3
4
5
|
function generate_code( $length = 4) { $min = pow(10 , ( $length - 1)); $max = pow(10, $length ) - 1; return rand( $min , $max ); } |