Page 1 of 1

leading zero's

Posted: Sun Aug 16, 2009 3:45 am
by arminium
Hi guys

Having trouble with leading zero's

I need to create a drop down with a loop for days of month

and i need a leading zero for first 9 days of the month i have this code, but after 01, it reverts to just 2 where it should be 02

Code: Select all

$sd="01";
        if(isset($dobd)){
        $dobd = $dobd;
        }else{
        $dobd = int(00);
        }
        while($sd<=31){
            echo"<option value=\"";
            sprintf("%02d",$sd);
            echo "\"";
            if($sd == $dobd){echo " selected ";}
            echo ">".$sd."</option>";
            $sd++;
        }
Any Ideas?

Re: leading zero's

Posted: Sun Aug 16, 2009 3:53 am
by neuroxik
Because it is going to be treated as a string anyway (seeing you're shooting it in a form ) you can always do a check for the string length, and if not equal to what it should be, add the zero's, like: (considering you want ONE leading zero if strlen is 1 )

Code: Select all

 
function padZero($n) {
    if(strlen($n) == 1) return "0".$n;
    else return $n;
}
 
edit: oh, and if you wanna force it in, just change line 12 to this:

Code: Select all

echo ">".padZero($sd)."</option>";

Re: leading zero's

Posted: Sun Aug 16, 2009 5:00 am
by Eran
you can also use str_pad()

Re: leading zero's

Posted: Sun Aug 16, 2009 5:21 am
by arminium
Thanks Guys

works now

using

Code: Select all

$sd=1;
        if(isset($dobd)){
        $dobd = $dobd;
        }else{
        $dobd = '00';
        }
        while($sd<=31){
            if(strlen($sd) == 1) {$sd = "0".$sd;}
            echo "<option value=\"".$sd."\"";
            if($sd == $dobd){echo " selected ";}
            echo ">".$sd."</option>";
            $sd++;
        }

Re: leading zero's

Posted: Sun Aug 16, 2009 9:40 am
by neuroxik
pytrin wrote:you can also use str_pad()
Oh... never used that, will save me some time next time :)

Re: leading zero's

Posted: Sun Aug 16, 2009 6:19 pm
by arminium
that looks simpler, will try that

thanks