0

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

Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
malik ali
  • 11
  • 1
  • 3

3 Answers3

5

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);

mayersdesign
  • 5,062
  • 4
  • 35
  • 47
  • i want 14 digit number ex: 11222233334444 – malik ali May 13 '17 at 06:59
  • @malikali And that's exactly what this answer does. – Terry May 13 '17 at 07:01
  • and i want to save in sql table like if user type i want o generate 20 numbers set – malik ali May 13 '17 at 07:06
  • Fatal error: Cannot redeclare generateCode() (previously declared in D:\xampp\htdocs\working\ihsan-sports\ms-panel\add-process\code-process.php:29) in D:\xampp\htdocs\working\ihsan-sports\ms-panel\add-process\code-process.php on line 29 facing this error – malik ali May 13 '17 at 07:07
  • Hi Malik, I don't think that's related to the code I posted. It sounds like you pasted the function twice. See: http://stackoverflow.com/questions/1953857/fatal-error-cannot-redeclare-function – mayersdesign May 13 '17 at 07:55
  • you redeclearing same named function. Need to turn off previous one. – Asif Uddin May 13 '17 at 08:35
0

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.

Rahul K
  • 413
  • 3
  • 11
0

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;
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42