732

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?

Andromeda
  • 12,659
  • 20
  • 77
  • 103

11 Answers11

1472

Use sprintf :

sprintf('%08d', 1234567);

Alternatively you can also use str_pad:

str_pad($value, 8, '0', STR_PAD_LEFT);
Zanshin13
  • 980
  • 4
  • 19
  • 39
reko_t
  • 55,302
  • 10
  • 87
  • 77
  • 69
    Just wanted to add: str_pad is not an option with negative numbers – wtf8_decode Jan 12 '15 at 19:23
  • 6
    Just to add on top of what wtf8_decode said; Negative numbers would not have leading zeros, and they are not positive numbers. i.e. 08 would be written as such as a date, or something which expects a positive double digit number (Bank Account sort code etc). Please correct me if I'm wrong, but as far as I know, there is no real life instance of requiring a leading zero on a negative value? – guyver4mk Mar 14 '16 at 09:24
  • 4
    Wanted to add that `sprintf('%+03d:00 UTC',$i)` where `$i` is -12 to 12, will print + or - as needed, and will also put leading zeros for numbers less than 2 digits. Great for making a timezone `SELECT` in HTML. – Volomike Aug 08 '16 at 04:22
  • 2
    for the current version (7.1) and lower `sprintf`(https://3v4l.org/junvv/perf#output) is a little bit faster than `str_pad`(https://3v4l.org/cliNP/perf#output) – Vladyslav Startsev Jun 22 '17 at 00:08
  • 2
    When might a negative number require a leading zero... A lift-off counter with three digits? T-010, T-009, T-008 etc. – TRT 1968 Mar 06 '19 at 16:05
  • Note that variable type casting comes into play here. When I concatenated a `sprintf` _integer_ with leading zeroes with a leading _string_ (`$new = 'PT'.$integerWithZeroes`) it represented the zeroes as spaces. When I used `str_pad` to create `$integerWithZeroes`, all worked well. _i.e._ `PT00000001` – Parapluie Jul 02 '19 at 20:11
  • Note that this is for the OP's 8 digits, if you just need 2 you change the pattern to `'%02d'` – jave.web Mar 16 '21 at 14:03
97

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

Logan Murphy
  • 6,120
  • 3
  • 24
  • 42
Kaze no Koe
  • 3,254
  • 1
  • 21
  • 22
94

When I need 01 instead of 1, the following worked for me:

$number = 1;
$number = str_pad($number, 2, '0', STR_PAD_LEFT);
Pang
  • 9,564
  • 146
  • 81
  • 122
Md. Shafiqur Rahman
  • 2,878
  • 27
  • 24
30
echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
joan16v
  • 5,055
  • 4
  • 49
  • 49
22

sprintf is what you need.

EDIT (somehow requested by the downvotes), from the page linked above, here's a sample "zero-padded integers":

<?php
    $isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>
  • 3
    Would be better with an example or more explanation beyond simply linking the man page for sprintf(). – jharrell Sep 13 '14 at 20:04
22

Though I'm not really sure what you want to do you are probably looking for sprintf.

This would be:

$value = sprintf( '%08d', 1234567 );
Adi
  • 5,089
  • 6
  • 33
  • 47
Huppie
  • 11,263
  • 4
  • 32
  • 34
14

Simple answer

$p = 1234567;
$p = sprintf("%08d",$p);

I'm not sure how to interpret the comment saying "It will never be more than 8 digits" and if it's referring to the input or the output. If it refers to the output you would have to have an additional substr() call to clip the string.

To clip the first 8 digits

$p = substr(sprintf('%08d', $p),0,8);

To clip the last 8 digits

$p = substr(sprintf('%08d', $p),-8,8);
Peter Lindqvist
  • 10,122
  • 3
  • 41
  • 60
11

If the input numbers have always 7 or 8 digits, you can also use

$str = ($input < 10000000) ? 0 . $input : $input;

I ran some tests and get that this would be up to double as fast as str_pad or sprintf.
If the input can have any length, then you could also use

$str = substr('00000000' . $input, -8);

This is not as fast as the other one, but should also be a little bit faster than str_pad and sprintf.

Btw: My test also said that sprintf is a little faster than str_pad. I made all tests with PHP 5.6.

Edit: Altough the substr version seems to be still very fast (PHP 7.2), it also is broken in case your input can be longer than the length you want to pad to. E.g. you want to pad to 3 digits and your input has 4 than substr('0000' . '1234', -3) = '234' will only result in the last 3 digits

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
3
$no_of_digit = 10;
$number = 123;

$length = strlen((string)$number);
for($i = $length;$i<$no_of_digit;$i++)
{
    $number = '0'.$number;
}

echo $number; ///////  result 0000000123
1

I wrote this simple function to produce this format: 01:00:03

Seconds are always shown (even if zero). Minutes are shown if greater than zero or if hours or days are required. Hours are shown if greater than zero or if days are required. Days are shown if greater than zero.

function formatSeconds($secs) {
    $result = '';

    $seconds = intval($secs) % 60;
    $minutes = (intval($secs) / 60) % 60;
    $hours = (intval($secs) / 3600) % 24;
    $days = intval(intval($secs) / (3600*24));

    if ($days > 0) {
        $result = str_pad($days, 2, '0', STR_PAD_LEFT) . ':';
    } 

    if(($hours > 0) || ($result!="")) {
        $result .= str_pad($hours, 2, '0', STR_PAD_LEFT) . ':';
    } 

    if (($minutes > 0) || ($result!="")) {
        $result .= str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':';
    } 

    //seconds aways shown
    $result .= str_pad($seconds, 2, '0', STR_PAD_LEFT); 

    return $result;

} //funct

Examples:

echo formatSeconds(15); //15
echo formatSeconds(100); //01:40
echo formatSeconds(10800); //03:00:00 (mins shown even if zero)
echo formatSeconds(10000000); //115:17:46:40 
Enigma Plus
  • 1,519
  • 22
  • 33
-1

You can always abuse type juggling:

function zpad(int $value, int $pad): string {
    return substr(1, $value + 10 ** $pad);
}

This wont work as expected if either 10 ** pad > INT_MAX or value >= 10 * pad.

jgmjgm
  • 4,240
  • 1
  • 25
  • 18