Dave S.
Dave S.

Reputation: 63

Is there a way to start a foreach loop in the middle of an array?

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

Answers (3)

Christian N.
Christian N.

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

Nick
Nick

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

Demo on 3v4l.org

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

Demo on 3v4l.org

Upvotes: 4

A l w a y s S u n n y
A l w a y s S u n n y

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

Related Questions