1

I have this method :

public function getYears($startYear = 1990, $endYear = date ('Y')){
    $years = [];
    $date = new \DateTime();

    $years[$date->format('Y')] = $date->format('Y'); 
    while ($endYear <= $startYear){
       $date->add(new \DateInterval('P1Y'));
       $years[$date->format('Y')] = $date->format('Y');
       $endYear++;
    }
   return $years;
}

This piece of code doens't work, but you get the idea what I want ? How can i make this work ? thx

Attila Naghi
  • 2,535
  • 6
  • 37
  • 59
  • Possible duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Fky Mar 20 '17 at 15:25
  • @Fky The post that you suggested is using the `strtotime` method. I want to use the methods from `DateTime()` class . Thx – Attila Naghi Mar 20 '17 at 15:26
  • Why not just use PHP's [range](http://php.net/range) function? – mrun Mar 20 '17 at 15:29
  • @Chester ALWAYS read a little bit more than just the accepted answer! – Pieter van den Ham Mar 20 '17 at 15:50

2 Answers2

4

If I understand your question, this is really easy:

$arYears = range(1990, date('Y'));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Mihai
  • 26,325
  • 7
  • 66
  • 81
1

If you want to stick with a loop, you can do it this way:

function getYears($startYear = 1990, $endYear = date ('Y')) {
  $years = [];
  for ($y = $startYear; $y < $endYear; $y++) {
    $years[] = $y;
  }
  return $years;
}
JM-AGMS
  • 1,670
  • 1
  • 15
  • 33