2

I have this code that will print name of month up to current month, if the year is current year and print up to december, if its not the current year.

The code is working, but I would like to ask:

  • Is there any shortest code to get the same result?

$current_year = date("Y");
$current_month  = date('n'); 
$year=2015;


if ($year==$current_year )
{
for($m=1; $m<=$current_month; ++$m){
    $monthName=date('F', mktime(0, 0, 0, $m, 1)).'<br />';
//print up to current month 
echo $monthName;
    }
}   
else
{

for($m=1; $m<=12; ++$m){
    $monthName=date('F', mktime(0, 0, 0, $m, 1)).'<br />';
//print up to December
echo $monthName;
    }   

}
gtroop
  • 295
  • 4
  • 13
  • Possible duplicate of [How to list all months between two dates](https://stackoverflow.com/questions/18742998/how-to-list-all-months-between-two-dates) – caramba Jul 03 '17 at 11:11

4 Answers4

2

You do not need two for loops. You just need check one if condition and set value for current month accordingly.

$current_year = date("Y");
$current_month = date('n'); 
$year=2015;

if($year!=$current_year)
  $current_month = 12;

for($m=1; $m<=$current_month; ++$m){
  $monthName=date('F', mktime(0, 0, 0, $m, 1)).'<br />';
  //print up to current month 
  echo $monthName;
}
pravid
  • 719
  • 9
  • 27
1

You simply need to decide up front where you will end your list...

if ($year==$current_year ) {
   $endMonth=$current_month;
}
else {
   $endMonth=12;
}

for($m=1; $m<=$endMonth; ++$m){
    $monthName=date('F', mktime(0, 0, 0, $m, 1)).'<br />';
    echo $monthName;
    }   

You could abbreviate the first bit to...

   $endMonth=($year==$current_year)?$current_month:12;
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
1

You can use only one loop and you need to break loop using only one if condition for the current year.

$current_year = date("Y");
$current_month  = date('n');
$year=2017;

for ($m=1; $m<=12; ++$m) {
    if ($year==$current_year && $m>$current_month) {
        break;
    }
    $monthName=date('F', mktime(0, 0, 0, $m, 1)).'<br />';
    echo $monthName;
}
Ravi Sachaniya
  • 1,641
  • 18
  • 20
1

instead of use for loop 2 times you can use a max variable and put that in for loop... I mean to say...

$current_year = date("Y");
$current_month  = date('n'); 
$year=2015;
if ($year==$current_year )$max= $current_month;
else $max = 12;
for($m=1; $m<=$max; ++$m){
    $monthName=date('F', mktime(0, 0, 0, $m, 1)).'<br />';
    echo $monthName;
}
GYaN
  • 2,327
  • 4
  • 19
  • 39