Reputation: 63
I have an array of months. I want to iterate through each month as the key to get the values for each one but...
I want to start at the current month, run the foreach and come back around to the next year stopping on the 12th month.
I've tried creating a separate array of months based on the current month, but it seems a little janky.
Upvotes: 5
Views: 812
Reputation: 11
Why not using for
statement instead?
$months = [
'January',
'February',
'...',
];
$currentMonth = 5; // 0 for January, 11 for December
for($i = 0; $i < 12; $i++) {
$index = ($currentMonth + $i) % 12;
echo $months[$index] . PHP_EOL;
}
Will print
June
July
August
September
...
Upvotes: 1
Reputation: 147206
You could use a do/while
loop with a modulo counter e.g.
$months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
$i = $current_month = 5;
do {
echo $months[$i] . "\n";
$i = ($i + 1) % 12;
} while ($i != $current_month);
Output:
Jun
Jul
Aug
Sep
Oct
Nov
Dec
Jan
Feb
Mar
Apr
May
If you also need to maintain a year counter, you can use this code, which increments the year when the month wraps around:
$year = 2018;
$i = $current_month = 5;
do {
echo $months[$i] . " $year\n";
$i = ($i + 1) % 12;
if ($i == 0) $year++;
} while ($i != $current_month);
Output:
Jun 2018
...
Dec 2018
Jan 2019
...
May 2019
Upvotes: 4
Reputation: 38532
You can try with continue
statement!
$current_month = 6; # just assuming, you can change as per your requirement.
foreach ($month_array as $k => $v) {
if ($k < 5) continue;
// your code here to go after your current month to end of the year's month
}
Upvotes: 1