musclehead Posted February 1, 2008 Share Posted February 1, 2008 I'm trying to write a simple loop to generate the date in format YYYY-MM, starting in April 2007 and incrementing to the current date. This probably awful-looking code generates all the months from 04/2007 until today: for ($i = 4; $i < 14; $i++){ echo date("Y-m",mktime(0,0,0,date("$i"),0,2007))."<br>"; } If I change the threshold of the "i" variable to 16, the loop will very nicely display January and February of 2008. However, that is a hard-coded value (along w/ the year) and will stop when the month changes to March. I know there's probably something simple to get this script to stop on the current month, but I've been staring at this for too long and can't wrap my head around it anymore! Thanks everyone! Quote Link to comment https://forums.phpfreaks.com/topic/88882-solved-incrementing-date-loop/ Share on other sites More sharing options...
musclehead Posted February 1, 2008 Author Share Posted February 1, 2008 Solved my own problem...coffee break not staring at the screen did the trick! $c = date("n"); for ($i = 4; $i < (14 + $c); $i++){ echo date("Y-m",mktime(0,0,0,date("$i"),0,2007))."<br>"; } Quote Link to comment https://forums.phpfreaks.com/topic/88882-solved-incrementing-date-loop/#findComment-455276 Share on other sites More sharing options...
laffin Posted February 1, 2008 Share Posted February 1, 2008 <?php function array_datetotoday($startdate) { $ldate=strtotime($startdate); $edate=strtotime(date("Y-m")); do { $dates[]=date("Y-m",$ldate); $ldate=strtotime("+1 Month",$ldate); }while($ldate <= $edate); return $dates; } $date_array = array_datetotoday(date("Y-m",strtotime("-1 Year"))); foreach($date_array as $dt) echo "$dt<br>"; ?> Quote Link to comment https://forums.phpfreaks.com/topic/88882-solved-incrementing-date-loop/#findComment-455286 Share on other sites More sharing options...
kenrbnsn Posted February 1, 2008 Share Posted February 1, 2008 I realized you said this is "Solved", but here is a solution that uses the strtotime() function: <?php $end = time(); $test = strtotime('2007-04-01'); while ($test <= $end) { echo date('Y-m',$test) . "<br>\n"; $test = strtotime('+1 month',$test); } ?> Ken Quote Link to comment https://forums.phpfreaks.com/topic/88882-solved-incrementing-date-loop/#findComment-455290 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.