A while ago I needed to automatically zero fill a number for a quoting system I was working on. I decided to browse the internet to search for a simple code snippit but I could only find code with a while loop that would keep adding zeroes untill the desired string length was reached. Although this seemed okay, I realized it could be done much cleaner, and most important, less draining for system resources. So I wrote the following function.
function zerofill ($num, $zerofill = 5) { return str_pad($num, $zerofill, '0', STR_PAD_LEFT); }
This function can be used like this.
echo zerofill(6, 3); // The output wil be 006 echo zerofill(49); // The output wil be 00049
I did a quick test for 1000 numbers with a function using a while loop and one with PHP’s str_pad function. I compared them by recording the microtime before and after the function and the str_pad version was somewhat faster. So I spared two lines of code and some time on it.
If you want to remove the padded zeroes again you can get the integer value of the string with the intval function.
$num = '00049'; echo intval($num); // Echoes 49
Or, just use printf() or sprintf():
Most things anyone wants to do at a string formatting level have already been done better.
I used to use sprintf but now I use str_pad. I think it’s more logical to use a function that was intended for the specific purpose.