100

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?

0

22 Answers 22

229

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);
Sign up to request clarification or add additional context in comments.

2 Comments

A bit cleaner way: $digits = 3; echo random_int( 10 ** ( $digits - 1 ), ( 10 ** $digits ) - 1);
I decide to benchmark the comment by @Mr.Jo with the actual answer, here are the results base on total execution time in nanoseconds: 5 Number=> marcusVersion(): 36,916 ns; mrJoVersion(): 27,769 ns 10 Number=> marcusVersion(): 11,116 ns; mrJoVersion(): 41,748 ns 15 Number=> marcusVersion(): 17,543 ns; mrJoVersion(): 60,442 ns 20 Number=> marcusVersion(): 20,373 ns; mrJoVersion(): 77,534 ns Your choice should dependent on how many numbers you're generating at a time
57

I usually just use RAND() http://php.net/manual/en/function.rand.php

e.g.

rand ( 10000 , 99999 );

for your 5 digit random number

1 Comment

This will never generate 0 as first digit.
23

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

2 Comments

Well, shuffling seems a good idea but it will not generate repeating number/character such as 2312, abcb, etc...
@PranavRaut This allows repeated number/characters: (say $digits is 5) substr(str_shuffle(str_repeat("0123456789", $digits)), 0, $digits);
14

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

3 Comments

The OP is asking for a number with $x digits, not a number between some number and $x.
he doesn't know a min/max, only the length of the to be expected number in digits
it always gives 1000
10

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

Comments

9

the simplest way i can think of is using rand function with str_pad

<?php
echo str_pad(rand(0,999), 5, "0", STR_PAD_LEFT);
?>

In above example , it will generate random number in range 0 to 999.

And having 5 digits.

1 Comment

I think this is the most suitable and efficient solution mentioned so far. It does not use any loops, does not use a shuffle which guarantees that numbers can exist multiple times in the result, does not need a lot of code to guarantee that the result contains x digits.
7
function random_numbers($digits) {
    $min = pow(10, $digits - 1);
    $max = pow(10, $digits) - 1;
    return mt_rand($min, $max);
}

Tested here.

4 Comments

will this output numbers with leading zeros too?
Do you need it to have leading zeros? It's already x digits long. Edit: Nevermind, I think I understand you. No, it will not create a number like "093".
is that hard to change? guess it doesnt matter.
If you want to allow numbers like "00937" for a 5-digit number, no it's not hard to change.
6

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

1 Comment

The OP is asking for a method to create a random number with x digits in it. Maybe you could edit you answer to match the question?
5

Well you can use as simple php function mt_rand(2000,9000) which can generate a 4 digit random number

mt_rand(2000,9000) 

Comments

4

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 : <?php echo mt_rand(); ?>

read more

Comments

2

do it with a loop:

function randomWithLength($length){

    $number = '';
    for ($i = 0; $i < $length; $i++){
        $number .= rand(0,9);
    }

    return (int)$number;

}

Comments

2

rand or mt_rand will do...

usage:

rand(min, max);

mt_rand(min, max);

1 Comment

OP is looking for a way to create a random number with x digits in it; could you adapt your answer to provide an example of how to use rand or mt_rand to do this?
2
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;  
}

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.
2

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

Comments

0

this simple script will do

$x = 4;//want number of digits for the random number
$sum = 0;


for($i=0;$i<$x;$i++)
{
    $sum = $sum + rand(0,9)*pow(10,$i);

}

echo $sum;

Comments

0

This is another simple solution to generate random number of N digits:

$number_of_digits = 10;
echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);

Check it here: http://codepad.org/pyVvNiof

Comments

0
function rand_number_available($already_mem_array,$boundary_min,$boundary_max,$digits_num)
{

    $already_mem_array_dim = count($already_mem_array);         // dimension of array, that contain occupied elements

    // --- creating Boundaries and possible Errors
    if( empty($digits_num) ){   
            $boundary_dim = $boundary_max - $boundary_min;
            if($boundary_dim <= 0){
                $error = -1;                                    // Error that might happen. Difference between $boundary_max and $boundary_min must be positive
            }else{
                $error = -2;                                    // Error that might happen. All numbers between, $boundary_min and $boundary_max , are occupied, by $already_mem_array
            }                                   
    }else{
            if($digits_num < 0){                                // Error. If exist, $digits_num must be, 1,2,3 or higher
                $error = -3; 
            }elseif($digits_num == 1){                          // if 'one-figure' number
                $error = -4;                                    // Error that might happen. All 'one-figure' numbers    are occupied, by $already_mem_array
                $boundary_min = 0;
                $boundary_max = 9;
                $boundary_dim = $boundary_max-$boundary_min;
            }elseif($digits_num == 2){                          // if 'two-figure' number
                $error = -5;                                    // Error that might happen. All 'two-figure' numbers    are occupied, by $already_mem_array
                $boundary_min = 10;
                $boundary_max = 99;
                $boundary_dim = $boundary_max-$boundary_min;
            }elseif($digits_num>2){                             // if 'X-figure' number. X>2
                $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 <= $boundary_dim)   &&  $boundary_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;
    // -------------------------------------------------------------------

}

Comments

0

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

Comments

0

Please not that rand() does not generate a cryptographically secure value according to the docs:

http://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: http://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.

5 Comments

Can you explain what you mean by a secure number?
A cryptographically secure random number is harder for a hacker to predict. Remember, random number generation is not truly random. For example, if the the random number is used to create a pin, you need it secure to prevent a hacker figuring it out. If the random number is for animations, then there is no fear if a hacker could predict what random number is going to be.
Thanks for your response. I’ll have to take a deeper look into random numbers generation. This: Remember random number generation is not truly random got me confused again. You mean because there would definitely be a pattern or an algorithm working under the hood? And if that’s what you mean, won’t hiding the generation process be enough security?
This may help: paragonie.com/blog/2015/07/… Random number generators are based on a seed value. If you know the seed value, you will know the order of all the random numbers. I'm unsure how cryptographically random numbers are implemented, but they are more secure than weak random number generators.
Thanks for that. I’ll read through and see if I can learn something new.
0

The following code generates a 4 digits random number:

echo sprintf( "%04d", rand(0,9999));

1 Comment

echo sprintf() is an "antipattern". There is absolutely no reason that anyone should ever write echo sprintf() -- it should be printf() without echo every time. This answer is not tailored to accommodate the asker's dynamic requirement.
-1

This will generate random 5 digit numbers and include numbers that start with zero.

$newCode = rand(0, 9) . rand (1000, 9999);

Comments

-2

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.

1 Comment

This does not answer the OP question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.