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')
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));
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);
$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"
}
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);