Reputation: 1835
I need to list all remaining months after the 15th of current month.
E.g. if today is the 15th of June, the remaining months are July, August, September, October, November, December.
I don't want to store the number of months, assign an IDs in a DB table because that won't be efficient.
How do I do this in PHP?
So far, I have thwe following which gives me the current month.
$todaysmonth= date('F');
Do I follow with a nested IFs? Or is there a better way?
Upvotes: 1
Views: 1082
Reputation: 107
Here we will be using DatePeriod which allows iteration over a set of dates and times, recurring at regular intervals, over a given period.
So we got the end date and we have the start date and then calculated the interval. And then looping over the period we got the array of months.
// current date : 20 Feb 2019
$startDate = new \DateTime('first day of next month');
$endDate = new \DateTime('1st january next year');
$interval = new \DateInterval('P1M');
$period = new \DatePeriod($startDate, $interval, $endDate);
// Start array with current date
$dates = [];
// Add all remaining dates to array
foreach ($period as $date) {
array_push($dates, $date->Format('F'));
}
// output
print_r($dates); die;
Array ( [0] => March [1] => April [2] => May [3] => June [4] => July
[5] => August [6] => September [7] => October [8] => November [9] =>
December )
Upvotes: 0
Reputation:
Get the current month number from the date, and make a loop to get months name.
$todaysmonth = date('n', strtotime("15 June 2016"));
for($i = $todaysmonth; $i <= 12; $i++){
$dateObj = DateTime::createFromFormat('!m', $i);
echo $monthName = $dateObj->format('F');
}
Upvotes: 1