breq
breq

Reputation: 25536

How to list last 12 months

I want to list 12 months from today. Ther's missing a few months ..

$i = 12;
while ($i > 0) {
    $ym = date('Y-m', strtotime("-$i month"));
    $yms [$ym] = $ym;

    $i--;
}

print_r($yms);

online example: http://codepad.org/XDv4iR3u

Upvotes: 1

Views: 2871

Answers (3)

mleko
mleko

Reputation: 12233

Use Datetime and DateInterval

<?php
$t = new Datetime();
$interval = new DateInterval("P1M");
for($i=0;$i<12;$i++){
    echo $t->sub($interval)->format('Y-m')."\n";
}

https://ideone.com/oQ0FRO

Upvotes: 1

Sam Dufel
Sam Dufel

Reputation: 17598

You'll want to to explicitly start from the beginning of the current month. Since we're currently on the 31st, you'll miss any months which have fewer than 31 days.

<?php
$i = 12;
while ($i > 0) {
    $ym = @date('Y-m', strtotime(date('Y-m-01') . " -$i month"));
    $yms [$ym] = $ym;

    $i--;
}

print_r($yms);
?>

Upvotes: 0

user1978142
user1978142

Reputation: 7948

You forgot to provide the current ym inside strtotime. Consider this example:

$yms = array();
$now = date('Y-m');
for($x = 12; $x >= 1; $x--) {
    $ym = date('Y-m', strtotime($now . " -$x month"));
    $yms[$ym] = $ym;
}

echo "<pre>";
print_r($yms);
echo "</pre>";

Sample Output:

Array
(
    [2013-05] => 2013-05
    [2013-06] => 2013-06
    [2013-07] => 2013-07
    [2013-08] => 2013-08
    [2013-09] => 2013-09
    [2013-10] => 2013-10
    [2013-11] => 2013-11
    [2013-12] => 2013-12
    [2014-01] => 2014-01
    [2014-02] => 2014-02
    [2014-03] => 2014-03
    [2014-04] => 2014-04
)

Upvotes: 2

Related Questions