Leading Zeros

If you’re familiar with the sprintf function, you may already know this or perhaps, just like for me, it will be a novelty.
I was looking for a fast way of adding leading zeros to a number determined on a loop, for example, I want to call 40 images dynamically and while I know that they follow this format for example image_XXX where the x’s are replaced by a number leaded by zeros if it’s smaller than 3 digits I had no easy way of adding those zeros.

I just dumbly assumed that the only way was checking the string length, and if it equalled to 1 add two leading zeros, if it equalled to 2 add just one and if it was 3 or bigger, don’t add any. That’s fast enough, and it can be done like this:

1
2
3
4
5
switch(strlen($number)){
case '1': $number = "00".$number; break;
case '2': $number = "0".$number; break;
default: $number = $number;
}

But that’s taking up 5 lines of code just for that small formatting, and imagine the implications of the same example but on a 10 digit number. So I found you can do the following with the same result and in just one line of code:

1
sprintf("%03d",$number);

Enjoy!

Update:

It was used for answering this question on the 13th of Novemeber.

No posts at the moment. Check back again later!

About Juan

Hola! Me llamo Juan y soy un programador de 23 años de Madrid. Este es mi blog personal dedicado a la programación en general aunque con cierta predilección hacia PHP y Java.