As noted above when subtracting months, results can be suspect. I needed to create an array of end of month dates for 6 months starting at Oct and going back. Using:
<?php
//Instantiate array
$dateset = [];
//Create new date object
$date = new \DateTime('2018-10-31);
//Add to array
$dateset[] = $date->format('Y-m-d');
//Go back 5 months
$nbr = 6;
for($i = 1; $i < $nbr; $i++){
$date->sub(new \DateInterval('P1M'));
$dateset[] = $date->format('Y-m-d');
}
?>
Results in:
array:6 [▼
0 => "2018-10-31"
1 => "2018-10-01"
2 => "2018-09-01"
3 => "2018-08-01"
4 => "2018-07-01"
5 => "2018-06-01"
]
However, using ->modify("last day of last month") accurately gives month ending dates:
<?php
//Instantiate array
$dateset = [];
//Create new date object
$date = new \DateTime('2018-10-31);
//Add to array
$dateset[] = $date->format('Y-m-d');
//Go back 5 months
$nbr = 6;
for($i = 1; $i < $nbr; $i++){
$date->modify('last day of last month');
$dateset[] = $date->format('Y-m-d');
}
?>
Results in:
array:6 [▼
0 => "2018-10-31"
1 => "2018-09-30"
2 => "2018-08-31"
3 => "2018-07-31"
4 => "2018-06-30"
5 => "2018-05-31"
]