Formatting a number with leading zeros in PHP [duplicate]

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?


Solution 1:

Use sprintf :

sprintf('%08d', 1234567);

Alternatively you can also use str_pad:

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

Solution 2:

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