I need to create a random number with x amount of digits.
So lets say x is 5, I need a number to be eg. 35562 If x is 3, then it would throw back something like; 463
Could someone show me how this is done?
asked Nov 21, 2011 at 17:35
user1022585user1022585
12.5k19 gold badges53 silver badges74 bronze badges
0
You can use rand[]
together with pow[]
to make this happen:
$digits = 3;
echo rand[pow[10, $digits-1], pow[10, $digits]-1];
This will output a number between 100 and 999. This because 10^2 = 100 and 10^3 = 1000 and then you need to subtract it with one to get it in the desired range.
If 005 also is a valid example you'd use the following code to pad it with leading zeros:
$digits = 3;
echo str_pad[rand[0, pow[10, $digits]-1], $digits, '0', STR_PAD_LEFT];
answered Nov 21, 2011 at 17:38
3
Here is a simple solution without any loops or any hassle which will allow you to create random string with characters, numbers or even with special symbols.
$randomNum = substr[str_shuffle["0123456789"], 0, $x];
where $x
can be number of digits
Eg. substr[str_shuffle["0123456789"], 0, 5];
Results after a couple of executions
98450
79324
23017
04317
26479
You can use the same code to generate random string also, like this
$randomNum=substr[str_shuffle["0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ"], 0, $x];
Results with $x = 11
FgHmqpTR3Ox
O9BsNgcPJDb
1v8Aw5b6H7f
haH40dmAxZf
0EpvHL5lTKr
answered Jun 13, 2017 at 13:56
Akshay KhaleAkshay Khale
7,8718 gold badges49 silver badges58 bronze badges
1
You can use rand[$min, $max]
for that exact purpose.
In order to limit the values to values with x digits you can use the following:
$x = 3; // Amount of digits
$min = pow[10,$x];
$max = pow[10,$x+1]-1];
$value = rand[$min, $max];
answered Nov 21, 2011 at 17:37
halfdanhalfdan
32.8k8 gold badges76 silver badges86 bronze badges
3
Treat your number as a list of digits and just append a random digit each time:
function n_digit_random[$digits] {
$temp = "";
for [$i = 0; $i < $digits; $i++] {
$temp .= rand[0, 9];
}
return [int]$temp;
}
Or a purely numerical solution:
function n_digit_random[$digits]
return rand[pow[10, $digits - 1] - 1, pow[10, $digits] - 1];
}
answered Nov 21, 2011 at 17:37
BlenderBlender
280k52 gold badges427 silver badges487 bronze badges
the simplest way i can think of is using rand
function with str_pad
In above example , it will generate random number in range 0 to 999.
And having 5 digits.
answered May 30, 2015 at 14:19
1
function random_numbers[$digits] {
$min = pow[10, $digits - 1];
$max = pow[10, $digits] - 1;
return mt_rand[$min, $max];
}
Tested here.
answered Nov 21, 2011 at 17:40
animuson♦animuson
52.8k28 gold badges139 silver badges145 bronze badges
4
rand[1000, 9999];
works more faster than x4 times rand[0,9];
benchmark:
rand[1000, 9999] : 0.147 sec.
rand[0,9]x4 times : 0.547 sec.
both functions was running in 100000 iterations to make results more explicit
answered Feb 21, 2017 at 16:36
AlexAlex
3314 silver badges9 bronze badges
1
Well you can use as simple php function mt_rand[2000,9000] which can generate a 4 digit random number
mt_rand[2000,9000]
answered Jun 19, 2019 at 11:22
Anoop P SAnoop P S
7041 gold badge11 silver badges30 bronze badges
do it with a loop:
function randomWithLength[$length]{
$number = '';
for [$i = 0; $i < $length; $i++]{
$number .= rand[0,9];
}
return [int]$number;
}
answered Nov 21, 2011 at 17:39
Rene PotRene Pot
24.2k7 gold badges67 silver badges90 bronze badges
0
rand
or mt_rand
will do...
usage:
rand[min, max];
mt_rand[min, max];
answered Nov 21, 2011 at 17:40
easybeasyb
681 silver badge8 bronze badges
1
function random_number[$size = 5]
{
$random_number='';
$count=0;
while [$count < $size ]
{
$random_digit = mt_rand[0, 9];
$random_number .= $random_digit;
$count++;
}
return $random_number;
}
answered Mar 30, 2016 at 8:26
1
You can generate any x-digit random number with mt_rand[]
function.
mt_rand[]
is faster than rand[]
.
Syntax : mt_rand[]
or mt_rand[$min , $max]
.
Example :
read more
statosdotcom
3,0792 gold badges16 silver badges38 bronze badges
answered Sep 4, 2019 at 9:43
Following is simple method to generate specific length verification code. Length can be specified, by default, it generates 4 digit code.
function get_sms_token[$length = 4] {
return rand[
[[int] str_pad[1, $length, 0, STR_PAD_RIGHT]],
[[int] str_pad[9, $length, 9, STR_PAD_RIGHT]]
];
}
echo get_sms_token[6];
answered May 26, 2020 at 15:46
this simple script will do
$x = 4;//want number of digits for the random number
$sum = 0;
for[$i=0;$i2
$error = -6; // Error that might happen. All 'X-figure' numbers are occupied, by $already_mem_array. Unlikely to happen
$boundary_min = pow[10, $digits_num-1]; // stepenovanje - graduation
$boundary_max = pow[10, $digits_num]-1;
$boundary_dim = $boundary_max-$boundary_min;
}
}
// -------------------------------------------------------------------
// --- creating response ---------------------------------------------
if[ [$already_mem_array_dim 0 ]{ // go here only if, there are AVAILABLE numbers to extract, and [difference] $boundary_dim , is positive
do{
$num = rand[$boundary_min,$boundary_max];
}while[ in_array[$num, $already_mem_array] ];
$result = $num;
}else{
$result = $error; // Limit that happened
}
return $result;
// -------------------------------------------------------------------
}
answered Feb 18, 2017 at 15:31
This function works perfectly with no repeats and desired number of digits.
$digits = '';
function randomDigits[$length]{
$numbers = range[0,9];
shuffle[$numbers];
for[$i = 0; $i < $length; $i++]{
global $digits;
$digits .= $numbers[$i];
}
return $digits;
}
You can call the function and pass the number of digits for example:
randomDigits[4];
sample results:
4957 8710 6730 6082 2987 2041 6721
Original script got from this gist
answered Jul 29, 2018 at 9:15
Reagan OchoraReagan Ochora
1,4571 gold badge18 silver badges19 bronze badges
Please not that rand[]
does not generate a cryptographically secure value according to the docs:
//php.net/manual/en/function.rand.php
This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int[], random_bytes[], or openssl_random_pseudo_bytes[] instead.
Instead it is better to use random_int[]
, available on PHP 7 [See: //php.net/manual/en/function.random-int.php].
So to extend @Marcus's answer, you should use:
function generateSecureRandomNumber[$digits]: int {
return random_int[pow[10, $digits - 1], pow[10, $digits] - 1];
}
function generateSecureRandomNumberWithPadding[$digits]: string {
$randomNumber = random_int[0, pow[10, $digits] - 1];
return str_pad[$randomNumber, $digits, '0', STR_PAD_LEFT];
}
Note that using
rand[]
is fine if you don't need a secure random number.
answered Aug 23, 2018 at 10:10
Yahya UddinYahya Uddin
23.9k32 gold badges126 silver badges220 bronze badges
5
The following code generates a 4 digits random number:
echo sprintf[ "%04d", rand[0,9999]];
answered Jan 12, 2020 at 18:40
1
you people really likes to complicate things :]
the real problem is that the OP wants to, probably, add that to the end of some really big number. if not, there is no need I can think of for that to be required. as left zeros in any number is just, well, left zeroes.
so, just append the larger portion of that number as a math sum, not string.
e.g.
$x = "102384129" . complex_3_digit_random_string[];
simply becomes
$x = 102384129000 + rand[0, 999];
done.
answered Apr 2, 2014 at 23:03
gcbgcb
13.3k7 gold badges67 silver badges90 bronze badges
1