3
\$\begingroup\$

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++;
\$\endgroup\$
  • \$\begingroup\$ 3v4l.org/rCRLM would be my suggestion \$\endgroup\$ – naththedeveloper Jan 30 '18 at 11:22
  • \$\begingroup\$ @naththedeveloper I need to get the years in between aswell so 2019 to 2020 and 2017 to 2016. \$\endgroup\$ – Robbert Cognito Jan 30 '18 at 11:23
  • \$\begingroup\$ in which case, use 3v4l.org/mWCjn \$\endgroup\$ – naththedeveloper Jan 30 '18 at 11:24
2
\$\begingroup\$

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

\$\endgroup\$
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ – Robbert Cognito Jan 30 '18 at 11:42
  • \$\begingroup\$ @Robbert check my edited solution code and working link. \$\endgroup\$ – Anant Singh---Alive to Die Jan 30 '18 at 11:43
3
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.