Wednesday 15 February 2012

for loop - Strange occurance when looping through dates PHP -



for loop - Strange occurance when looping through dates PHP -

so loop through using list out months current going 11 months using

$dateformat = 'y-m'; $currentmonth = date($dateformat); $monthstogoback = 11; $months = array($currentmonth); for($m = 1;$m<=$monthstogoback;$m++){ $months[] = date($dateformat, strtotime("-".$m." months")); echo $m.'<br>'; }

the strangest thing happening when run script how array build there no feb double march. 1 have thought causing this.

array ( [0] => 2014-10 [1] => 2014-09 [2] => 2014-08 [3] => 2014-07 [4] => 2014-06 [5] => 2014-05 [6] => 2014-04 [7] => 2014-03 [8] => 2014-03 [9] => 2014-01 [10] => 2013-12 [11] => 2013-11 )

answer problem

for($m = 1;$m<=$monthstogoback;$m++){ $months[] = date($dateformat,strtotime(date('y-m') . '-01 -'.$m.' months')); }

this because substract number of seconds in month. unrealiable because there's no fixed amount of seconds in each month.

you need rewrite code. here tested example:

$currentyear = date('y'); $currentmonth = date('m'); $monthstogoback = 11; for($monthno = 0;$monthno <= $monthstogoback;$monthno++) { $months[] = $currentyear.'-'.str_pad($currentmonth,2,'0',str_pad_left); $currentmonth--; if ($currentmonth == 0) { $currentyear--; $currentmonth = 12; } } echo '<pre>'.print_r($months,true).'</pre>';

the output is:

array ( [0] => 2014-10 [1] => 2014-09 [2] => 2014-08 [3] => 2014-07 [4] => 2014-06 [5] => 2014-05 [6] => 2014-04 [7] => 2014-03 [8] => 2014-02 [9] => 2014-01 [10] => 2013-12 [11] => 2013-11 )

php for-loop

No comments:

Post a Comment