253

PHP - Is there a quick, on-the-fly method to test for a single character string, then prepend a leading zero?

Example:

$year = 11;
$month = 4;

$stamp = $year.add_single_zero_if_needed($month);  // Imaginary function

echo $stamp; // 1104
Ben
  • 54,723
  • 49
  • 178
  • 224
  • 3
    After testing, turns out sprintf() was a bit better: it has a common language format and doesn't use a class constant, among other things. – Ben Jan 15 '13 at 07:09

3 Answers3

603

You can use sprintf: http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>

It will only add the zero if it's less than the required number of characters.

Edit: As pointed out by @FelipeAls:

When working with numbers, you should use %d (rather than %s), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.

For example:

sprintf("%04s", 10); returns 0010
sprintf("%04s", -10); returns 0-10

Where as:

sprintf("%04d", 10); returns 0010
sprintf("%04d", -10); returns -010

Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
230

You can use str_pad for adding 0's

str_pad($month, 2, '0', STR_PAD_LEFT); 

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

likeitlikeit
  • 5,563
  • 5
  • 42
  • 56
Gaurav
  • 28,447
  • 8
  • 50
  • 80
18

The universal tool for string formatting, sprintf:

$stamp = sprintf('%s%02s', $year, $month);

http://php.net/manual/en/function.sprintf.php

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 2
    str_pad is more readable. I like keeping things simple. sprintf is great function, i use it a lot for transaltions, when there must be a variable in the middle of the string, but for such thing, i will go with str_pad(); while i'm working only with positive integers. they don't require any fancy stuff. – Lukas Liesis Apr 04 '15 at 21:49
  • Use sprintf: sprintf('%08d', 1234567); Alternatively you can also use str_pad: str_pad($value, 8, '0', STR_PAD_LEFT); – Kamlesh Sep 04 '19 at 16:32
  • what about signed digit ? str_replace("00", "0", sprintf('%03d', $num)) – Sahib Khan Jun 05 '20 at 06:19