Formatting a number with leading zeros in PHP

Andromeda picture Andromeda · Nov 9, 2009 · Viewed 557.7k times · Source

I have a variable which contains the value 1234567.

I would like it to contain exactly 8 digits, i.e. 01234567.

Is there a PHP function for that?

Answer

reko_t picture reko_t · Nov 9, 2009

Use sprintf :

sprintf('%08d', 1234567);

Alternatively you can also use str_pad:

str_pad($value, 8, '0', STR_PAD_LEFT);