Working with zero filled numbers in PHP
May 19, 2010 PHP Coding
A while ago I had posted some code to zero fill a number on another site I run. At the time it was the only way I knew of to perform that function. The code that I am referring to is listed below.
function zerofill ($num,$zerofill) { // Get the current string length of the original number // Loop through that number until it has reached the count in $zerofill while (strlen($num)<$zerofill) { $num = "0".$num; } return $num; }
And would be used such as:
// Output will be 005 echo zerofill(5, 3);
What this code does is takes 2 inputs, one for the number and the other for the length you want the number to be. As you see above we input the numbers 5 and 3 into the function arguments. The output of the function would return 005 and not 5.
One of the comments left on my older posting suggested to use the built in PHP function sprintf instead of the while loop. At the time that was posted I did not have the time to look into the proper usage of that function and then I lost track of things and never got around to checking it out. This is why I am posting this article now about using sprintf for zero filling a number. Using the same function name and arguments I have re-written the code for zero filling a number with the sprintf function.
function zerofill ($num, $zerofill = 3) { return sprintf("%0".$zerofill."s", $num); }
I did a very quick non intense test to see which code functioned faster with a loop of about 10,000 numbers recording the microtime before and after the loop then calculating the difference. The sprint function appears to be slightly faster.
Now that we have a function to add the zeros to a number you might want to remove said zero’s from the number for use someplace else. Below is a function that will do just that. Just enter the number you want to remove the zeros from as the only argument and it will return the newly formatted number.
function zeroremove($value) { return preg_replace("/(\.\d+?)0+$/", "$1", $value)*1; }
May 28th, 2010 at 10:01 am
Or just use:
str_pad($num, 3, “0″, STR_PAD_LEFT);
This is a built-in function which is just made to exactly that!