Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 200
Andromeda Avatar asked Nov 09 '09 09:11

Andromeda


People also ask

How can I pad a value with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

How do you convert a number to text and keep the leading zeros?

The first way to keep leading zeros in front of numbers is to put an apostrophe ' in front of the number. Notice how I input '0123 and not just 0123. Now, when I hit Enter, the number will keep its leading zero. In the cell, all we see is the number; the apostrophe has become invisible.


2 Answers

Use sprintf :

sprintf('%08d', 1234567); 

Alternatively you can also use str_pad:

str_pad($value, 8, '0', STR_PAD_LEFT); 
like image 56
reko_t Avatar answered Sep 27 '22 21:09

reko_t


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

like image 41
Kaze no Koe Avatar answered Sep 27 '22 20:09

Kaze no Koe