How To Add Leading Zeros To A Number In PHP?

Discover how to correctly format numbers with leading zeros in PHP

  • By Daniyal Hamid
  • May 27, 2017
  • Comments
In This Article

In PHP numbers with a leading zero are interpreted differently and may yield unexpected results. For example:

$num = 0123;  // is considered an octal number (that equals 83 decimal)
$num = 0x123; // is considered a hexadecimal number (that equals 291 decimal)
$num = 0b111; // is considered a binary number (that equals 7 decimal)

If you want to ensure that a prefixed zero sticks to a number without losing its "natural" meaning, then you could try some of the ways documented below.

Using A String Instead Of A Number

This is the simplest, no-brainer, approach; use a string to represent the number like so:

$str = "0123";

Or, alternatively, we could use the number as a string and prepend the required number of zeros to the start:

$num = 123;
$str = "0{$num}";

Use when:

  1. The length of the output string does NOT matter.
  2. You always want 0 (or a sequence of it) prepended to the number no matter what.

Using substr()

If you're alright with clipping the numbers on the left if the specified string length is exceeded, then you can simply use substr() like so:

$num = 123;
$str_length = 4;

// hardcoded left padding if number < $str_length
$str = substr("0000{$num}", -$str_length);

// output: 0123

Instead of hardcoding the zeros, we could also use str_repeat() like so:

$num = 12345;

// left padding as needed
$str = substr(str_repeat(0, $str_length) . $num, -$str_length);

// output: 2345

The obvious downside to this approach is that we clip the numbers on the left if the number exceeds the specified length.

Use when:

  1. The length of the output string strictly matters.
  2. You wish to add zeros only when the string is less than the specified length.
  3. It does not matter if numbers are clipped off the left side of the string when the string is greater than the specified length.

Using printf() / sprintf()

Returning String When Input Exceeds Padding Length:

To pad an output to a fixed length (for example, 4) when input is less than the padding length, and returning the string when input is greater, we could do the following:

$pad_length = 4;
$pad_char = 0;
$str_type = 'd'; // treats input as integer, and outputs as a (signed) decimal number

$format = "%{$pad_char}{$pad_length}{$str_type}"; // or "%04d"

// output and echo
printf($format, 123);

// output to a variable
$formatted_str = sprintf($format, 123);

// output: 0123
  • If string length is greater than or equal to the padding length, the whole string is returned — i.e. no characters are chopped off.
  • Please bear in mind that padding is only added when the length of the input string is smaller than the specified padding length.
  • Refer to the sprintf() function's documentation for all the formatting options.
  • There are slight differences between printf() and sprintf() which you can read up if you're interested.
Clipping String When Input Exceeds Padding Length:

If you wish to clip off numbers when the input is greater than the padding length, you could use the substr() function on the result returned by sprintf() like so:

// clip the first 4 digits
$output = substr(sprintf($format, 12345), 0, $pad_length); // output 1234

// clip the last 4 digits
$output = substr(sprintf($format, 12345), -$pad_length); // output 2345

This technique would only work on sprintf() as printf() would output/echo the result immediately when called.

Add Padding To Negative Numbers:

Imagine a use case where we wish to represent hour of the day using a 12-hour clock representation; we could use negative to denote night, and positive sign to denote day. In such a case, if we wanted to pad all numbers less than 10 to have a leading zero, we could do the following:

$pad_length = 3;
$pad_char = 0;
$str_type = 'd';

$format = "%+{$pad_char}{$pad_length}{$str_type}:00"; // or "%+03d:00"

$hr = -8; // hours between -12 to 12
$formatted_time = sprintf($format, $hr);

// output: -08:00

The + sign is just to ensure all positive values have a plus sign prepended.

Use when:

  1. You wish to add zeros only when the string is less than the specified length.
  2. You want the flexibility of clipping numbers from the left or right if need be.
  3. Your input may contain negative numbers.

Using str_pad()

Returning String When Input Exceeds Padding Length:

To pad an output to a fixed length (for example, 4) when input is less than the padding length, and returning the string when input is greater, we could do the following:

$pad_length = 4;
$pad_char = 0;

// output 0123
$str = str_pad(123, $pad_length, $pad_char, STR_PAD_LEFT);

// output 1234
$str = str_pad(1234, $pad_length, $pad_char, STR_PAD_LEFT);
  • If string length is greater than or equal to the padding length, the whole string is returned — i.e. no characters are chopped off.
  • The second argument to the function is used to specify the padding length; you must bear in mind that this will only add padding when the length of the input string is smaller than the specified padding length.
  • The function's output is a string.
  • If your output is going to have negative numbers, then you should avoid using str_pad() as it would yield results like 0-123 while you might be expecting -0123.
Clipping String When Input Exceeds Padding Length:

If you wish to clip off numbers when the input is greater than the padding length, you could use the substr() function like so:

$str = str_pad(12345, $pad_length, $pad_char, STR_PAD_LEFT);

// clip the first 4 digits
$output = substr($str, 0, $pad_length); // output 1234

// clip the last 4 digits
$output = substr($str, -$pad_length); // output 2345

Use when:

  1. Your input only contains positive numbers.
  2. You wish to add zeros only when the string is less than the specified length.
  3. You want the flexibility of clipping numbers from the left or right if need be.

If you think we've missed out on something or if you have another (or even better) way of adding leading zeros to a number in PHP, please let us know in the comments section below.


HashFlare
You Might Also Like
MinerGate
Genesis Mining