How do I Format a number with leading zeros in PHP

I want to be able to have a variable with a fixed number of digits. If the variable is less than the fixed number of digits I want to add some leading zeros. For example if I have a number 7654321 and I want the fixed number of digits to be eight the resulting variable should be 07654321

Is there a PHP function for that?

Thank

Bob from Germantown

One thought on “How do I Format a number with leading zeros in PHP

  1. Hello Bob
    There is a function in PHP that you can use to format your numbers with leading zeros. There are many different uses for this function and one of them happens to Specifying padding character to a string. It is called sprintf. The following is an example of how you would use it.
    sprintf('%08d', 7654321);

    Alternatively you can also use str_pad:
    str_pad($value, 8, '0', STR_PAD_LEFT);

Comments are closed.