# Setting PHP variables for 2 years back and 2 years in the future

The following code gets years (dates), 1 and 2 years back (for example 2017 - 2016) and 1 and 2 years into the future (for example 2019 - 2020). Now PHP is not my expertise so I would like to get some help cleaning this up.

Is there a different approach I should use when doing this?

//Filter jaren
$year = date("Y");$yearBack = $year;$yearBack--;
$yearDoubleBack =$yearBack;
$yearDoubleBack--;$yearAhead = $year;$yearAhead++;
$YearDoubleAhead =$yearAhead;
$YearDoubleAhead++;  • 3v4l.org/rCRLM would be my suggestion – naththedeveloper Jan 30 '18 at 11:22 • @naththedeveloper I need to get the years in between aswell so 2019 to 2020 and 2017 to 2016. – Robbert Cognito Jan 30 '18 at 11:23 • in which case, use 3v4l.org/mWCjn – naththedeveloper Jan 30 '18 at 11:24 ## 3 Answers Only three-four line code rquired for getting required result:- <?php$date = date("Y"); //current year

$date_range = range($date-2, $date+2);//get year range //print_r($date_range); //print year range

echo implode(',',$date_range);//comma seperated date range  Output:- https://eval.in/944817 • Its still the same exact question. I need a clean way to get the years from 2 years ago and 2 years into the future. For example: 2016, 2017, 2018, 2019, 2020 – Robbert Cognito Jan 30 '18 at 11:42 • @Robbert check my edited solution code and working link. – Alive to Die Jan 30 '18 at 11:43 Use the DateTime class from PHP. <?php$current = new DateTime(date('Y'));

$current->modify("-2 year"); echo$current->format("Y");
//outputs 2016
$current->modify("+4 year"); echo$current->format("Y");
//outputs 2020


You can simply add and subtract the years:

<?php

$year = date("Y");$yearDoubleBack = date("Y", strtotime($year . " - 2 year"));$YearDoubleAhead = date("Y", strtotime($year . " + 2 year")); echo '$yearDoubleBack => ' . $yearDoubleBack; echo PHP_EOL; echo '$YearDoubleAhead => ' . $YearDoubleAhead; echo PHP_EOL;$years = range($yearDoubleBack,$YearDoubleAhead);
print_r(\$years);


Check : https://3v4l.org/DLmql