Formatting a number with leading zeros in PHP


Question

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?

1
551
8/10/2017 4:00:44 AM

Accepted Answer

Use sprintf :

sprintf('%08d', 1234567);

Alternatively you can also use str_pad:

str_pad($value, 8, '0', STR_PAD_LEFT);
1106
3/29/2016 2:16:34 PM

Given that the value is in $value:

  • To echo it:

    printf("%08d", $value);

  • To get it:

    $formatted_value = sprintf("%08d", $value);

That should do the trick


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon