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); 
Share:
37,521
dotty
Author by

dotty

Hmm not alot really.

Updated on June 16, 2020

Comments

  • dotty
    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
    Tom Haigh almost 15 years
    This pads to the right of the number, and pads with spaces not zeros. $padded = str_pad($number, $width, 0, STR_PAD_LEFT);
  • Joe
    Joe almost 15 years
    Yeah, 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
    Jack Henahan over 10 years
    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.
  • Nuri Akman
    Nuri Akman over 5 years
    If you want to Zero Pad for 15 digits, should be like this: $filled_int = sprintf("%015d", $your_int)