1

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 eventually going to be added to a string do i need to cast the int as a string?)

thanks

5 Answers 5

12

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.
1
  • +1. Nice dissection of the format string. I always have to look them up :-)
    – Joey
    Oct 23, 2009 at 14:12
6
sprintf("%04d", rand(0,9999))

should do what you want

3
  • damn it. one second too late -.-
    – Etan
    Oct 23, 2009 at 14:05
  • 1
    actually you have like a million rep points im going to give it to etan
    – Crash893
    Oct 23, 2009 at 14:08
  • Aww. I've hit the rep cap for today a few hours ago anyway. So whether it's 215 or 230 doesn't make much of a difference :-)
    – Joey
    Oct 23, 2009 at 14:12
3

Quick and dirty... how about doing:

rand(10000,19999)

and take the last four digits:

substr(rand(10000, 19999), 1, 4)
3
  • 1
    Smart! I must say. Thinking out of the box.
    – o.k.w
    Oct 23, 2009 at 14:06
  • 1
    Although this will work, coming across this in code is going to make me pause and wonder what is going on. Oct 23, 2009 at 14:06
  • @LFSR: You're absolutely right, which is why it's quick and "dirty". :-) Oct 23, 2009 at 14:07
3
str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);

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

1

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.