chaseman Posted February 26, 2011 Share Posted February 26, 2011 This for loop: for ($m = 01; $m <= 12; $m++) Will output: 1 2 3 4 etc. And NOT: 01 02 03 04 My question is: how can I make the number be 2 digits and have it output together with the ZERO? And when it's reaching the number 10 it should continue outputting: 10 11 12 And not 010 011 etc. Quote Link to comment https://forums.phpfreaks.com/topic/228945-keep-zero-in-front-of-digit/ Share on other sites More sharing options...
Altrozero Posted February 26, 2011 Share Posted February 26, 2011 Not pretty, but it works. for ($m = 1; $m <= 12; $m++) { $use = $m; if($m < 10) $use = '0'.$m; echo $use; } Quote Link to comment https://forums.phpfreaks.com/topic/228945-keep-zero-in-front-of-digit/#findComment-1180085 Share on other sites More sharing options...
chaseman Posted February 26, 2011 Author Share Posted February 26, 2011 Thanks for the tip, this is how I solved it in my specific example: if ($d < 10) { $zero_d = '0'. $d; } else { $zero_d = $d; } The else statement was important in my case otherwise it would output: 09 09 09 09 Instead of 09 10 11 12 Quote Link to comment https://forums.phpfreaks.com/topic/228945-keep-zero-in-front-of-digit/#findComment-1180089 Share on other sites More sharing options...
ignace Posted February 26, 2011 Share Posted February 26, 2011 for($i = 1; $i <= 12; ++$i) printf('%02d', $i); Quote Link to comment https://forums.phpfreaks.com/topic/228945-keep-zero-in-front-of-digit/#findComment-1180090 Share on other sites More sharing options...
Cagecrawler Posted February 26, 2011 Share Posted February 26, 2011 You can also use the str_pad as a simpler version of printf. echo str_pad($m, 2, '0', STR_PAD_LEFT); Quote Link to comment https://forums.phpfreaks.com/topic/228945-keep-zero-in-front-of-digit/#findComment-1180096 Share on other sites More sharing options...
chaseman Posted February 26, 2011 Author Share Posted February 26, 2011 for($i = 1; $i <= 12; ++$i) printf('%02d', $i); Pretty elegant solution, thanks a lot. Quote Link to comment https://forums.phpfreaks.com/topic/228945-keep-zero-in-front-of-digit/#findComment-1180105 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.