To find the last day of the month you can use t
as the format parameter supplied to the date()
function. To find the 15th of the month generate the time using mktime
and convert to a date with required output format.
/* Initial date and duration of processing */
$start = '2019-01-21';
$months = 4;
/* reduce start date to it's constituent parts */
$year = date('Y',strtotime($start));
$month = date('m',strtotime($start));
$day = date('d',strtotime($start));
/* store results */
$output=array();
for( $i=0; $i < $months; $i++ ){
/* Get the 15th of the month */
$output[]=date('Y-m-d', mktime( 0, 0, 0, $month + $i, 15, $year ) );
/* Get the last day of the calendar month */
$output[]=date('Y-m-t', mktime( 0, 0, 0, $month + $i, 1, $year ) );
}
/* use the results somehow... */
printf('<pre>%s</pre>',print_r($output,true));
Outputs:
Array
(
[0] => 2019-01-15
[1] => 2019-01-31
[2] => 2019-02-15
[3] => 2019-02-28
[4] => 2019-03-15
[5] => 2019-03-31
[6] => 2019-04-15
[7] => 2019-04-30
)
If, as the comment below suggests, you would prefer that the dates begin with the month end rather than the 15th of the month simply change the order within the loop that calculated dates are added to the output array...
for( $i=0; $i < $months; $i++ ){
/* Get the last day of the calendar month */
$output[]=date('Y-m-t', mktime( 0, 0, 0, $month + $i, 1, $year ) );
/* Get the 15th of the month */
$output[]=date('Y-m-d', mktime( 0, 0, 0, $month + $i, 15, $year ) );
}
output:
Array
(
[0] => 2019-01-31
[1] => 2019-01-15
[2] => 2019-02-28
[3] => 2019-02-15
[4] => 2019-03-31
[5] => 2019-03-15
[6] => 2019-04-30
[7] => 2019-04-15
)
To output the results in the exact format of the example results
$format=(object)array(
'last' => 't-M-y',
'15th' => 'd-M-y'
);
for( $i=0; $i < $months; $i++ ){
/* Get the last day of the calendar month */
$output[]=date( $format->{'last'}, mktime( 0, 0, 0, $month + $i, 1, $year ) );
/* Get the 15th of the month */
$output[]=date( $format->{'15th'}, mktime( 0, 0, 0, $month + $i, 15, $year ) );
}
output:
Array
(
[0] => 31-Jan-19
[1] => 15-Jan-19
[2] => 28-Feb-19
[3] => 15-Feb-19
[4] => 31-Mar-19
[5] => 15-Mar-19
[6] => 30-Apr-19
[7] => 15-Apr-19
)