2

I have an integer that I need to convert into a 4 digits string. I know the integer number is between 1 and 9999. If the number is 4, I want the output string to be "0004". If the number is 134, I need the string output as "0134" and so on.

What would be the shortest most elegant way of achieving this in PHP? Thank you.

Marcos Buarque
  • 3,318
  • 8
  • 44
  • 46

6 Answers6

13

I would use sprintf():

$string = sprintf( "%04d", $number);

Using this demo:

foreach( array( 4, 134) as $number) {
    $string = sprintf( "%04d", $number);
    echo $string . "\n";
}

You get as output:

0004
0134
nickb
  • 59,313
  • 13
  • 108
  • 143
3

Try this

 $num = 1;
 $paddedNum = sprintf("%04d", $num);
 echo $paddedNum;
chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
  • Thank you for the answer. Your answer and the chosen one arrived at the same time and I had to choose one of them. I picked the first one on my list. Thanks you very much anyway, I have upvoted you! – Marcos Buarque Apr 12 '13 at 18:00
2

Try this

str_pad($input, 4, "0", STR_PAD_LEFT);

This will work for integer and string both

Amit
  • 1,365
  • 8
  • 15
1

http://php.net/manual/de/function.str-pad.php

$input = 9;
$str = str_pad($input, 4, "0", STR_PAD_LEFT); //results in 0009
dognose
  • 20,360
  • 9
  • 61
  • 107
1

You can use sprintf with the %d option:

$NewString = sprintf( "%04d", $OldNumber);

the 04 tells sprintf how many digits your number should be, and will fill with zeros if it doesn't reach that number.

Borniet
  • 3,544
  • 4
  • 24
  • 33
1
$num = rand(1,9999);
echo sprintf( "%04d", $num);

Try this.

som
  • 4,650
  • 2
  • 21
  • 36
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. – mickmackusa Apr 09 '22 at 06:06