php random x digit number - Stack Overflow

PHOTO EMBED

Sun Jun 25 2023 10:58:34 GMT+0000 (Coordinated Universal Time)

Saved by @ajay579

You can use rand() together with pow() to make this happen:

$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);
 Save
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);
 Save
Share
Improve this answer
Follow
content_copyCOPY

https://stackoverflow.com/questions/8215979/php-random-x-digit-number