36

How would I go about 'zero filling' an integer?

ie

1 becomes 0001
40 becomes 0040
174 becomes 0174
BenMorel
  • 34,448
  • 50
  • 182
  • 322
dotty
  • 40,405
  • 66
  • 150
  • 195

2 Answers2

86
$filled_int = sprintf("%04d", $your_int)
Palantir
  • 23,820
  • 10
  • 76
  • 86
25
$number = 12;
$width = 4;
$padded = str_pad((string)$number, $width, "0", STR_PAD_LEFT); 
Joe
  • 46,419
  • 33
  • 155
  • 245
  • 1
    This pads to the right of the number, and pads with spaces not zeros. $padded = str_pad($number, $width, 0, STR_PAD_LEFT); – Tom Haigh Sep 18 '09 at 10:09
  • Yeah, ommission on my part. Corrected. But I would retain some semblance of type safety by providing appropriate types (even if conversion is automatic). – Joe Sep 18 '09 at 10:32
  • 2
    Depending on the scenario, I'd say this is usually the better solution. Additionally, it is not currently necessary to explicitly cast to `string` unless you use a numeric literal in `str_pad`. A variable of a numeric type will be implicitly cast. – Jack Henahan Mar 16 '14 at 22:28