Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Pad Numbers in PHP (See related posts)

Sometimes I need numbers to always be two digits, even if they're less than 10. The below snippet will format all numbers to be two digits, inserting a 0 if they're under 10 - creating, for example, 09 instead of 9.

$raw = 1;
$formatted = sprintf("%02d", $raw);
echo $formatted;

//outputs 01

Comments on this post

MellerTime posts on Jun 20, 2006 at 19:17
You could also use str_pad...

$raw = 1;
$formatted = str_pad($raw, 2, 0, STR_PAD_LEFT);
echo $formatted;

// should output 01


Longer, yes, but you don't have to remember funky stuff like %02d. Besides, I'd never remember what that line of code did later on when I was looking back at it...
ndmpatriot posts on Aug 02, 2006 at 21:11
Where would I place this in the code?
nothingless posts on Aug 26, 2006 at 17:01
Inbetween the <? and ?>, just above where you want to echo the padded number. :)

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts