How to zero fill a number in PHP

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 my own function.

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

Author: Luc De Brouwer

Mild-mannered software engineer, Nine Inch Nails lover, gin drinker, cat person, and somewhat of a geek. Ron Swanson is my spirit animal.

2 thoughts on “How to zero fill a number in PHP”

Comments are closed.