Add Leading Zeros to a Number in PHP

Adding leading zeroes to a number can be useful in various situations. For example, if you need to format a number for printing in a certain way, you can use leading zeroes to make sure that all of the digits are shown. This can be especially helpful when you’re working with numbers that are too large or too small to be shown in their entirety.

In PHP, there are a few different ways that you can add leading zeroes to a number.

  • One option is to use the printf() or sprintf() function. This function allows you to specify a format for how a value should be displayed, and it will return a string with the formatted value.
  • The str_pad() method pads a string with another to make it longer. You can tell the function how many spaces there should be on each side of the text by giving it an argument. But if you don’t, it will add spaces on either side until the text is the specified length. If you don’t give it any other instructions, it will also take up all available space before and after the text.
  • With the substr() method, you can easily extract a portion of your text in any direction. It will start at position 0 if you don’t provide any values or it’ll go up +1 every time through.
echo str_pad('27', 4, "0", STR_PAD_LEFT); //0027
echo str_pad('12', 3, "0", STR_PAD_LEFT); //012
echo str_pad('5', 2, "0", STR_PAD_LEFT); //05

printf("%03d", 89); //089
printf("%10d", 12345); //0000012345
echo sprintf("%06d", 22334); //022334
echo sprintf("%8d", 444555); //00444555

$number = 15;
$length = 3;
$result = substr(str_repeat(0, $length).$number, - $length); //015

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.