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?
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.
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.)
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.
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.
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).
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.
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With