35

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

ie

1 becomes 0001
40 becomes 0040
174 becomes 0174
1

2 Answers 2

85
$filled_int = sprintf("%04d", $your_int)
1
  • 2
    If you want to Zero Pad for 15 digits, should be like this: $filled_int = sprintf("%015d", $your_int)
    – Nuri Akman
    Nov 29, 2018 at 8:21
25
$number = 12;
$width = 4;
$padded = str_pad((string)$number, $width, "0", STR_PAD_LEFT); 
3
  • 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, 2009 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, 2009 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. Mar 16, 2014 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.