leading zero's

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
arminium
Forum Newbie
Posts: 18
Joined: Wed Aug 12, 2009 10:02 pm
Location: Sunshine Coast, AUSTRALIA!!!!!!

leading zero's

Post 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?
User avatar
neuroxik
Forum Commoner
Posts: 25
Joined: Tue Aug 11, 2009 10:32 pm

Re: leading zero's

Post 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>";
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: leading zero's

Post by Eran »

you can also use str_pad()
User avatar
arminium
Forum Newbie
Posts: 18
Joined: Wed Aug 12, 2009 10:02 pm
Location: Sunshine Coast, AUSTRALIA!!!!!!

Re: leading zero's

Post 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++;
        }
User avatar
neuroxik
Forum Commoner
Posts: 25
Joined: Tue Aug 11, 2009 10:32 pm

Re: leading zero's

Post by neuroxik »

pytrin wrote:you can also use str_pad()
Oh... never used that, will save me some time next time :)
User avatar
arminium
Forum Newbie
Posts: 18
Joined: Wed Aug 12, 2009 10:02 pm
Location: Sunshine Coast, AUSTRALIA!!!!!!

Re: leading zero's

Post by arminium »

that looks simpler, will try that

thanks
Post Reply