开发者

simple rand() question

开发者 https://www.devze.com 2022-12-09 20:05 出处:网络
I need a random 4 digit number right now im using rand(1000,9999) that always gives me a 4 digit number but i eliminates 0000-0999 as possible results.

I need a random 4 digit number

right now im using rand(1000,9999) that always gives me a 4 digit number but i eliminates 0000-0999 as possible results.

how do you pad a random number?

(also this is even开发者_开发问答tually going to be added to a string do i need to cast the int as a string?)

thanks


In scripting languages like PHP, you don't have to cast in 99% of the cases.

Padding could be done using

sprintf("%04u", rand(0, 9999));

Explanations

the first argument of sprintf specifies the format

  • % stays for the second, third, forth etc. argument. the first % gets replaced by the second argument, the second % by the third etc.
  • 0 stays for the behaviour of filling with 0 to the left.
  • 4 stays for "At least 4 characters should be printed"
  • u stays for unsigned integer.


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

should do what you want


Quick and dirty... how about doing:

rand(10000,19999)

and take the last four digits:

substr(rand(10000, 19999), 1, 4)


str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);

Use mt_rand() instead of rand(), it's better.


You can use str_pad() or sprintf() to format your string:

$rand = rand(0, 9999);
$str1 = str_pad($rand, 4, '0', STR_PAD_LEFT);
$str2 = sprintf('%04u', $rand);
0

精彩评论

暂无评论...
验证码 换一张
取 消