Reputation: 95
I'm having a problem, im trying to generate a 5 or 7 characters long number code with php, but the following code does include letters, i only need numbers, thanks in advance
$newgid = substr(md5(microtime()),rand(0,9),5);
Upvotes: 1
Views: 15776
Reputation: 1388
To future readers who come across this, I would recommend something like the following:
function generateNumericString(INT $len, STRING $str = '') {
if (strlen($str) < $len) {
return generateNumericString($len, $str . random_int(0, 9));
}
return $str;
}
Rather than using a loop, the function above uses recursion; it calls itself continuously, adding a single digit to the string, until the string length reaches the specified value. Anywhere and anytime you want you can generate a string of any length (i.e. 5) simply by calling:
generateNumericString(5);
Additionally, this method allows for the first digit in the sequence to include 0.
Although I prefer the first method, if you know you will absolutely never need more than 5 numbers in the string you can technically achieve the same thing with:
$n = substr(random_int(100000, 199999), 1);
This generates a 6 digit integer, then casts it as a string and returns everything after the first digit. Removing the first digit preserves 0 as a possible first character.
EDIT: random_int()
is used in place of other methods to ensure generated numbers are cryptographically secure.
Upvotes: 1
Reputation: 49
function createPin($len){
$maxNbrStr = str_repeat('9',$len);
$maxNbr = intval($maxNbrStr);
$n = mt_rand(0, $maxNbr);
$pin = str_pad($n, $len, "0", STR_PAD_LEFT);
return $pin;
}
Here's a short & sweet function that will produce a string of numbers at the desired length.
Upvotes: 1
Reputation:
If you don't mind that the numbers start from 10000 instead of zero, this is the shortest way:
mt_rand(10000, 99999)
Upvotes: 1
Reputation: 795
function randomPrefix($length=5) {
$random = "";
srand((double) microtime() * 1000000);
$data = "0123456789";
// $data = "A0B1C2DE3FG4HIJ5KLM6NOP7QR8ST9UVW0XYZ";
for ($i = 0; $i < $length; $i++) {
$random .= substr($data, (rand() % (strlen($data))), 1);
}
return $random;
}
Upvotes: 1
Reputation: 76646
I'd simply use mt_rand()
as follows:
<?php
$a = '';
for ($i = 0; $i<7; $i++)
{
$a .= mt_rand(0,9);
}
echo $a;
?>
Upvotes: 6
Reputation: 33512
You can use the following to generate a 5 digit code quite easily, and I am sure you can work out from here how to make it 7 digits long.
$string='';
for($i=0;$i<5;$i++)
{
$string.=rand(0,9);
}
echo $string;
Upvotes: 1
Reputation: 4446
I would use rand()
to generate number between 0 and 99999 and treat it as string.
$newgid = sprintf('%05d', rand(0, 99999));
Upvotes: 5