realjumper Posted February 22, 2007 Share Posted February 22, 2007 Hi, in this little loop I am getting the count of 0 - 31. It is giving '1,2,3,4,5,6,7,8,9,10 etc etc I would like the leading zero to be there for the single digit numbers, like this '01,02,03,04,05,06,07,08,09,10,11 etc etc. What am I not doing? for ($num=1; $num <= 31; $num++ ) { echo "<option value=\"$num\">$num</option>"; } Thanks :-) Link to comment https://forums.phpfreaks.com/topic/39698-solved-leading-zeros-in-for-loop/ Share on other sites More sharing options...
kenrbnsn Posted February 22, 2007 Share Posted February 22, 2007 Use the sprintf() function: <?php for ($num=1; $num < 32; $num++ ) echo '<option value="' . $num . '">' . sprintf("%02d",$num) . '</option>'; ?> Ken Link to comment https://forums.phpfreaks.com/topic/39698-solved-leading-zeros-in-for-loop/#findComment-191648 Share on other sites More sharing options...
realjumper Posted February 22, 2007 Author Share Posted February 22, 2007 Never mind, I got it. Sorry for ($num=1; $num <= 31; $num++ ) { if($num<10) $num = "0$num"; else $num="$num"; echo "<option value=\"$num\">$num</option>"; } [/code/ Link to comment https://forums.phpfreaks.com/topic/39698-solved-leading-zeros-in-for-loop/#findComment-191649 Share on other sites More sharing options...
realjumper Posted February 22, 2007 Author Share Posted February 22, 2007 Oh thanks kenrbnsn, I didn't know about that function. I'll look it up :-) Link to comment https://forums.phpfreaks.com/topic/39698-solved-leading-zeros-in-for-loop/#findComment-191651 Share on other sites More sharing options...
paul2463 Posted February 22, 2007 Share Posted February 22, 2007 you could write a simple function to pad the zero such as <?php function padzero($num) { if ($num < 10) { $num = "0$num"; } return $num; } //then for ($num=1; $num <= 31; $num++ ) { echo "<option value=\"$num\">padzero($num)</option>"; //value stays the same what is shown has padded zero } ?> Link to comment https://forums.phpfreaks.com/topic/39698-solved-leading-zeros-in-for-loop/#findComment-191657 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.