Wednesday 2 January 2019

Formatting a number with leading zeros in PHP



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?


Answer



Use sprintf :



sprintf('%08d', 1234567);



Alternatively you can also use str_pad:



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

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...