So here is an interesting problem I learned today.
I need to populate an array with the last 12 months, starting with the past month. So in August 2011, the last 12 months will be Sep 2010 - July 2011. To do this, I am using:
for ($i = 1; $i <= 12; $i++)
$months[] = date("Y-m%", strtotime("-$i months"));
The code above works just fine on August 30. I get the last 12 months:
array
0 => string '2011-07%' (length=8)
1 => string '2011-06%' (length=8)
2 => string '2011-05%' (length=8)
3 => string '2011-04%' (length=8)
4 => string '2011-03%' (length=8)
5 => string '2011-02%' (length=8)
6 => string '2011-01%' (length=8)
7 => string '2010-12%' (length=8)
8 => string '2010-11%' (length=8)
9 => string '2010-10%' (length=8)
10 => string '2010-09%' (length=8)
11 => string '2010-08%' (length=8)
But when I run this on Aug 31, I get:
array
0 => string '2011-07%' (length=8)
1 => string '2011-07%' (length=8)
2 => string '2011-05%' (length=8)
3 => string '2011-05%' (length=8)
4 => string '2011-03%' (length=8)
5 => string '2011-03%' (length=8)
6 => string '2011-01%' (length=8)
7 => string '2010-12%' (length=8)
8 => string '2010-12%' (length=8)
9 => string '2010-10%' (length=8)
10 => string '2010-10%' (length=8)
11 => string '2010-08%' (length=8)
I have tried both Windows and Unix. Does anyone have a solution for this?
I'm sure someone has a more elegant solution, but you could start counting backwards from the 1st of this month.
for ($i = 1; $i <= 12; $i++) {
$months[] = date("Y-m%", strtotime( date( 'Y-m-01' )." -$i months"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With