Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » Pad Number With Zeros

Pad Number With Zeros

Pad a number with zeros. Shows you how to achieve that using a function for reusability.

A simple way to use a function that pads a number with x amount of zeros.

function padWithZeros($s, $n) {
  return sprintf("%0" . $n . "d", $s);

We use sprintf() that accepts 2 arguments. The first one is the conversion string and the second is the string to convert. The conversion string starts with a "%" followed by a conversion in order. In this case we want to pad zeros to a point determined in calling the function.

To use this function you make a call like this

print padWithZeros("1", 5);

That pads the number 1 with four zeros to equal five places.

You can use sprintf for a series of tasks, including but not limited to padding, justification, custom padding etc...

Finally here is the function with a call in one place for easy copy & pasting.

function padWithZeros($s, $n) {
  return sprintf("%0" . $n . "d", $s);

print padWithZeros("1", 5);

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Pad Number With Zeros

 Car Broker  Fri Feb 23, 2007 8:47 pm  
Just what I was looking for! Thank you.
 mkeefe  Sun Feb 25, 2007 12:18 am  
Your welcome
 grad student  Wed Apr 18, 2007 6:53 pm  
thanks a lot! this worked quickly and flawlessly.
 mkeefe  Wed Apr 18, 2007 7:10 pm  
My pleasure, I like to hear back from the readers.
 pcal  Sat Jul 14, 2007 12:51 am  
Thank you.
I had many lines of awkward code to do the same thing.
 pete  Fri Dec 19, 2008 7:06 am  
Hi, you can just use "str_pad()" php function.
 Web Design Birmingham  Tue Jul 28, 2009 5:22 pm  
I'm with Pete on this one. Check out, it will save you a load of bother.
 David Newey  Wed Sep 8, 2010 2:38 pm  

Thank you for your function. I would like to know what the "%" and the "d" in the conversion string stand for.

Add a comment
The ability to add new comments has been disabled in this archived version.

Main | Tutorials | Articles