zerofill a integer php
37,521
Solution 1
$filled_int = sprintf("%04d", $your_int)
Solution 2
$number = 12;
$width = 4;
$padded = str_pad((string)$number, $width, "0", STR_PAD_LEFT);
Comments
-
dotty about 4 years
How would I go about 'zero filling' an integer?
ie
1 becomes 0001 40 becomes 0040 174 becomes 0174
-
Tom Haigh almost 15 yearsThis pads to the right of the number, and pads with spaces not zeros. $padded = str_pad($number, $width, 0, STR_PAD_LEFT);
-
Joe almost 15 yearsYeah, ommission on my part. Corrected. But I would retain some semblance of type safety by providing appropriate types (even if conversion is automatic).
-
Jack Henahan over 10 yearsDepending 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 instr_pad
. A variable of a numeric type will be implicitly cast. -
Nuri Akman over 5 yearsIf you want to Zero Pad for 15 digits, should be like this: $filled_int = sprintf("%015d", $your_int)