0

Is there any way to get the previous three months if I am giving the year and month as input (in PHP). Suppose I am giving the values,

$month = "2";
$year = 2016;

It should return like below array,

Array ( [0] => '11 2015' [1] => '12 2015' [2] => '01 2016')
Nuju
  • 322
  • 6
  • 17

4 Answers4

3

You mean something like this?

function getLastMonths($year, $month, $format = 'm Y', $amount = 3) {
  $months = [];
  $time = strtotime($year . '-' . $month . '-01 00:00:00');

  for ($i = 1; $i <= $amount; $i++) {
    $months[] = date($format, strtotime('-' . $i . ' month', $time));
  }

  return $months;
}

So you can use it like that

$month_array = getLastMonths('2017', '06');
var_dump($month_array);
UfguFugullu
  • 2,107
  • 13
  • 18
1

Use mktime

$month = "2";
$year = 2016;

for($i=3;$i>0;$i--){
    $arr[]=date("m-Y", mktime(0, 0, 0, $month-$i, 01, $year));


}
print_r($arr);

output

Array ( [0] => 11-2015 [1] => 12-2015 [2] => 01-2016 )

EDIT for your comment replace m with n

$arr[]=date("n-Y", mktime(0, 0, 0, $month-$i, 01, $year));
sumit
  • 15,003
  • 12
  • 69
  • 110
  • 1
    Perfect! Thank You! – Nuju Jun 01 '17 at 06:48
  • Instead of Array ( [0] => 11-2015 [1] => 12-2015 [2] => 01-2016 ), may I get Array ( [0] => 11-2015 [1] => 12-2015 [2] => 1-2016 ). Trim left zero from the month value. – Nuju Jun 01 '17 at 07:03
0
$month = "2";
$year  = 2016;

$result   = [];
$dateTime = DateTime::createFromFormat('Y n', "$year $month");
for($i = 0; $i < 3; $i++) {
    $dateTime->sub(new DateInterval('P1M'));
    $result[] = $dateTime->format('m Y');
}

var_dump(array_reverse($result));

Output

array(3) {
  [0]=>
  string(7) "11 2015"
  [1]=>
  string(7) "12 2015"
  [2]=>
  string(7) "01 2016"
}
Nikita U.
  • 3,540
  • 1
  • 28
  • 37
0

Just try this code:

$array = array();
$month = "2";
$year = 2016;
$number_of_months = 3;
for($i = 0; $i < $number_of_months; $i++):
    $sub_date   = date("m Y", strtotime($year."-".$month." -1 months"));
    $array[]    = $sub_date;
    $month      = explode(" ", $sub_date)[0];
    $year       = explode(" ", $sub_date)[1];
endfor;

print_r($array);