开发者

Generate integers with leading 0's

I have a project where I have to generate random numbers from 00000 till 99999. The randomizing isn't where I get stuck, but the fact that it always needs 5 characters is. So when it 开发者_StackOverflowgenerates the number 14, I want it as 00014.

What is the best way to achieve this?


sprintf() can do that:

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

Or use str_pad() - but that's a little bit longer in code:

echo str_pad(0, 5, 0, STR_PAD_LEFT);


str_pad() is able to do what you need the code to be done.

Simply:

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


generate integers with leading 0's

An integer will never have leading 0's.

If you need leading 0's you nedd to convert the integer to an string -> see the answer from thephpdeveloper. This is the right way for writing an number with leading 0's into a database - for example.

If you like to work with that integer (for example for calculations) it's better to leave the integer as an integer (don't change to string) and every time you need to output those numbers -> take the solution from "Stefan Gehrig"


Even substr() can do it:

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

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜