Generate integers with leading 0

I have a project where I have to generate random numbers from 00000 to 99999. Randomization is not where I get stuck, but that it always needs five characters. So when it generates the number 14, I want it to be 00014.

What is the best way to achieve this?

+3
source share
4 answers

sprintf() can do this:

 echo sprintf('%05d', 0); 

Or use str_pad() - but this is a bit more in code:

 echo str_pad(0, 5, 0, STR_PAD_LEFT); 
+11
source

str_pad() is capable of doing what you need, the code you need to execute.

Just:

 $s = str_pad('14', 5, '0', STR_PAD_LEFT); 
+6
source

generates integers with leading 0

An integer will never have 0.

If you need to cast 0, you will need to convert the integer to a string -> see answer from thephpdeveloper. This is the correct way to write a number with a leading 0 in the database - for example.

If you like to work with this integer (for example, for calculations), it is better to leave the integer as an integer (do not change to a string) and every time you need to print these numbers โ†’ make a decision from "Stefan Gerig"

+3
source

Even substr() can do this:

 print substr('0000' . $myRandomNumber, -5); 

(Not that I recommend this. I just wanted to contribute :))

0
source

All Articles