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
arminium
Forum Newbie
Posts: 18 Joined: Wed Aug 12, 2009 10:02 pm
Location: Sunshine Coast, AUSTRALIA!!!!!!
Post
by arminium » Sun Aug 16, 2009 3:45 am
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?
neuroxik
Forum Commoner
Posts: 25 Joined: Tue Aug 11, 2009 10:32 pm
Post
by neuroxik » Sun Aug 16, 2009 3:53 am
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>";
Eran
DevNet Master
Posts: 3549 Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME
Post
by Eran » Sun Aug 16, 2009 5:00 am
you can also use str_pad()
arminium
Forum Newbie
Posts: 18 Joined: Wed Aug 12, 2009 10:02 pm
Location: Sunshine Coast, AUSTRALIA!!!!!!
Post
by arminium » Sun Aug 16, 2009 5:21 am
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++;
}
neuroxik
Forum Commoner
Posts: 25 Joined: Tue Aug 11, 2009 10:32 pm
Post
by neuroxik » Sun Aug 16, 2009 9:40 am
pytrin wrote: you can also use str_pad()
Oh... never used that, will save me some time next time
arminium
Forum Newbie
Posts: 18 Joined: Wed Aug 12, 2009 10:02 pm
Location: Sunshine Coast, AUSTRALIA!!!!!!
Post
by arminium » Sun Aug 16, 2009 6:19 pm
that looks simpler, will try that
thanks