Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php random x digit number

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?

like image 334
user1022585 Avatar asked Nov 21 '11 17:11

user1022585


People also ask

How do I generate a random 4 digit number in PHP?

The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

How do I generate a random 6 digit number in PHP?

The rand () function is used to generate a random number in PHP. It can also be used to generate a random number within a specific range (for example a number between 10 and 30.)

What is Mt_rand function in PHP?

The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

How to generate 2 digit unique random number in PHP?

You can use the php rand () and mt_rand () function to generate 2,4,6,10,12, etc digit unique random number in PHP The PHP rand () is inbuilt PHP function.

How to generate any x-digit random number in Python?

you can generate any x-digit random number with mt_rand () function. mt_rand () much faster with rand () function syntax: mt_rand () or mt_rand ($min, $max).

How to generate random numbers or integers?

We can generate random numbers or integers using built-in functions. What do these functions do? These functions within a range of min and max generate different sets of numbers. And every time you call this function it will generate a number that is unique.

How do you get a random number in Python?

rand ( int $min , int $max ) : int. If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).


1 Answers

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); 
like image 136
Marcus Avatar answered Oct 05 '22 18:10

Marcus