awebbdesign Posted June 28, 2007 Share Posted June 28, 2007 I have the following.. for ($a = 01; $a < 13; $a++) { <option value='$a'>$a</option> } however it starts at 1, ideally I need it to print... 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12 I tried number_format but with no joy, any pointers? Link to comment https://forums.phpfreaks.com/topic/57546-solved-print-01-not-1-in-a-for-loop/ Share on other sites More sharing options...
HuggieBear Posted June 28, 2007 Share Posted June 28, 2007 Something like this? <?php for ($a = 1; $a < 13; $a++){ if ($a < 10){ $a = "0" . $a; } echo "<option value='$a'>$a</option>\n"; } ?> Regards Huggie Link to comment https://forums.phpfreaks.com/topic/57546-solved-print-01-not-1-in-a-for-loop/#findComment-284806 Share on other sites More sharing options...
no_one Posted June 28, 2007 Share Posted June 28, 2007 You might want to try sprintf(..) to format a print string. (or printf()); $af = sprintf("%'02d",$a); <option value='<?php echo $af; ?>'>..... You can look it up, but here's a quick overview. % starts the type specifier, d = integer. '0 indicates you want the number padded (the ') with 0's and the following 2 indicates you want it all printed 2 wide minimum, so that when you get into double digit numbers the padding will no longer be applied. Link to comment https://forums.phpfreaks.com/topic/57546-solved-print-01-not-1-in-a-for-loop/#findComment-284810 Share on other sites More sharing options...
bbaker Posted June 28, 2007 Share Posted June 28, 2007 if you need the output to look like this (with comma separation): 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12 <?php for ($a = 1; $a < 13; $a++) { $output[] = sprintf("%'02d",$a); } echo join(', ', $output); ?> if you need the output for a drop down list <select name="name"> <?php for ($a = 1; $a < 13; $a++) { $a = sprintf("%'02d",$a); echo "<option value=\"$a\">$a</option>\n"; } ?> </select> Link to comment https://forums.phpfreaks.com/topic/57546-solved-print-01-not-1-in-a-for-loop/#findComment-284814 Share on other sites More sharing options...
awebbdesign Posted June 28, 2007 Author Share Posted June 28, 2007 Cheers guys, I will learn more about this sprintf, many thanks Link to comment https://forums.phpfreaks.com/topic/57546-solved-print-01-not-1-in-a-for-loop/#findComment-284818 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.