I want to generate a random number code in PHP without repeat and with 16 lengths. What's the best way to do this? I use this code :
$possible = '0123456789';
$code = '';
$i = 0;
while ($i < 14) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
echo($code);
But that is generating 1 random number. I want 30000 random numbers. What shall I do ?
i use this code too but that is not generate 16 length :
<?php
$con=mysqli_connect("localhost","root","","test1");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
for ($s=0;$s<10;$s++) {
$possible = '0123456789';
$code = '';
$i = 0;
while ($i < 16) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
echo($code);
echo nl2br("$code <br/>");
mysqli_query($con,"INSERT INTO test (ID, Code, Type, Used)
VALUES ('', '".$code."','1', '0')");
}
for ($s=0;$s<10;$s++) {
$possible = '0123456789';
$code = '';
$i = 0;
while ($i < 16) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
echo($code);
echo nl2br("$code <br/>");
mysqli_query($con,"INSERT INTO test (ID, Code, Type, Used)
VALUES ('', '".$code."','2', '0')");
}
for ($s=0;$s<10;$s++) {
$possible = '0123456789';
$code = '';
$i = 0;
while ($i < 16) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
echo($code);
echo nl2br("$code <br/>");
mysqli_query($con,"INSERT INTO test (ID, Code, Type, Used)
VALUES ('', '".$code."','3', '0')");
}
mysqli_close($con);
?>
Snippet for no repeating digits:
$len=14;
$last=-1;
for ($i=0;$i<$len;$i++)
{
do
{
$next_digit=mt_rand(0,9);
}
while ($next_digit == $last);
$last=$next_digit;
$code.=$next_digit;
}
Snippet for no duplicates within 30000 (but repeating digits are allowed):
$codes=array();
while (count($codes) < 30000)
{
$code=rand(pow(10,13),pow(10,14)-1);
$codes["$code"]=1;
}
The codes are stored as the keys of the array (just to save some memory).
There might be better solutions for this problem (especially with more efficient ones) - but this one is really short ;-) - due to the integration of Kolink's solution.
Hope it helps a bit.
*Jost
A random 14-digit number may be generated simply by using rand(pow(10,13),pow(10,14)-1)
- PHP can handle integer values up to 251-1, since it silently converts them to double-precision floats if they get too big.