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 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

2 Replies to “How to zero fill a number in PHP”

  1. Or, just use printf() or sprintf():

    $z = sprintf('%03d', 6); // $z == '006' 

    Most things anyone wants to do at a string formatting level have already been done better.

Comments are closed.