I’d simplify that even further.
for ($i=0; $i<3; $i++) {
echo date('m',strtotime("+$i months",date('M Y')));
}
That way you only have four function calls instead of five.
I would also advise AGAINST using range, as that has to make an array in memory and define it’s values – WAY slower than a normal loop – and using more memory is never a good idea, even with such a small range.
– edit – in theory since we’re using the first of the month, you could ALWAYS add 31 days and get a valid month result, using even less function calls.
$target=strtotime(date('M Y'),time()-24*60*60);
for ($i=0; $i<3; $i++) {
echo date('m',$target);
$target+=2678400; // 1 month
}
Faster, but could break if you try to check more than 20 or so months in advance.
A hybrid:
$now=strtotime(date('M Y'));
for ($i=0; $i<3; $i++) {
echo date('m',strtotime("+$i months",$now));
}
At least gets the static value out of the loop. anything that remains the same should always be outside the loop, not inside.
… and yet another approach could be:
$target=strtotime(date('M Y'));
for ($i=0; $i<3; $i++) {
echo date('m',$target);
$target=strtotime('+1 months',$target);
}
Which doesn’t actually use the looping variable for the index.
though we’re REALLY overthinking the solution here to be honest:
$target=date('m');
for ($i=0; $i<3; $i++) {
echo str_pad($target,2,'0',STR_PAD_LEFT);
$target=($target%12)+1;
}
Is probably what I’d use. Pull the month FIRST as a number, then cut it off with modulus, then add one… guarantee simple math and str_pad to add the leading zero if needed is WAY faster than the endless calls to the time functions.