简体   繁体   中英

generate 14 digit random number in php

heres my code

while($x <= $num) {
$code = rand(1,666666).rand(2,88888888);

$INC = qry_run("Insert into ms_code2 (code) Values(".$code.")");

$x++;
} 

the main problem is when this loop work sometimes it generate 14 number sometimes 10 and sometimes 12

I won't get into a discussion about how "random" we can ever really get, I am pretty sure this will generate a number random enough! :)

function randomNumber($length) {
    $result = '';
    for($i = 0; $i < $length; $i++) {
        $result .= mt_rand(0, 9);
    }
    return $result;
}

..and of course then it's just echo randomNumber(14);

You can use this simple trick to generate (n) number of random numbers

function generateCode($limit){
    $code = 0;
    for($i = 0; $i < $limit; $i++) { $code .= mt_rand(0, 9); }
    return $code;
}
echo generateCode(14);

This above function returns 14 random digits.

A simplest one could be this also, Here we are using array_map and range to iterate over callback function and maintain a string.

Try this code snippet here

<?php

ini_set('display_errors', 1);

$string="";
array_map(function($value) use(&$string){
    $string.=mt_rand(0, 9);
}, range(0,13));
echo $string;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM