Home  >  Q&A  >  body text

Format numbers with leading zeros in PHP

<p>I have a variable that contains the value <code>1234567</code>. </p> <p>I want it to contain exactly 8 digits, which is <code>01234567</code>. </p> <p>Is there a PHP function? </p>
P粉101708623P粉101708623446 days ago562

reply all(2)I'll reply

  • P粉056618053

    P粉0566180532023-08-24 12:34:35

    Assume the value is in $value:

    • Echo it:

      printf(" d", $value);

    • Get it:

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

    This should do the trick

    reply
    0
  • P粉018653751

    P粉0186537512023-08-24 10:30:07

    Usesprintf:

    sprintf('%08d', 1234567);

    Alternatively, you can use str_pad< /a>:

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

    reply
    0
  • Cancelreply