[ View menu ]

Adding leading zeros in PHP

Written on March 20, 2007

function leadingZeros($num,$numDigits) {
   return sprintf("%0".$numDigits."d",$num);
}
 
echo leadingZeros(1,2);     // 01
echo leadingZeros(11,2);    // 11
echo leadingZeros(11,1);    // 11
echo leadingZeros(253,4);   // 0253

According to a post on the PHP.net page for str_pad(), sprintf() is much faster for this purpose.

Filed in: php, web development.

No Comments

Write comment - TrackBack - RSS Comments

You have to be logged in to post a comment.