Wednesday, 1 June 2011

Leading zero to numbers in PHP

Here's a simple code snippet to add leading zero to a number. How to add leading zero to date

#1

<?php 
function leadingzero ($num,$fill) { 
 while (strlen($num)<$fill) { 
         $num = "0".$num;
    }
    return $num; 
}
echo leadingzero(100, 3);
?>


Output: 000100

#2

<?php
$x = 1;
$y = sprintf("%03d",$x);
echo $y;
?>

Output: 001

#3

Print a day in double digit; Leading zero for first 9 days.

<?php
for ($num = 1; $num <= 31; $num++) {
if($num<10)
$day = "0$num"; // add the zero
else
$day = "$num"; // don't add the zero
echo "<p>$day</p>";
}
?>

Output:

01
02
03
04
05
06
07
08
09
10
.
.
.
31

No comments:

Post a Comment