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?
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.
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.
Use sprintf
:
sprintf('%08d', 1234567);
Alternatively you can also use str_pad
:
str_pad($value, 8, '0', STR_PAD_LEFT);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With