Home > Software design >  How to get the first and last day of each year in a loop with PHP?
How to get the first and last day of each year in a loop with PHP?

Time:10-07

I have a range of years, I want to know the first and last day or date of each year. because I need to calculate all activities that have been done in each years. here is my code:

$years = range(2015, date('Y'));

foreach ($years as $year) {

   echo "Number of activities" . $year . "<br/>";
}

I need to have the strat and end date or day of all years. I can get the first and last day in the way as below but it not a good salution:

// for 2015
$firstDayOfYear = date('Y-m-d', strtotime('first day of january 2015'));
$lastDayOfYear = date('Y-m-d', strtotime('last day of december 2015'));
// for 2016
$firstDayOfYear = date('Y-m-d', strtotime('first day of january 2016'));
$lastDayOfYear = date('Y-m-d', strtotime('last day of december 2016'));
.
.
.
// until 2021

When the number of year increase it's not possible manually. Because i need to display them in a chart. Can anybody help me pelease ?

CodePudding user response:

Check this out

$start_year = '2015';
$last_year = date('Y');

for($start_year; $start_year <= $last_year; $start_year  ){
    echo $firstDayOfYear = date('Y-m-d', strtotime("first day of january {$start_year}"));
    echo $lastDayOfYear = date('Y-m-d', strtotime("last day of december {$start_year}"));
}

CodePudding user response:

Try this solution:

$years = range(2015, date('Y'));

$array = [];

foreach ($years as $year) {

    echo "Number of activities " . $year . "<br/>";

    $obj = (object)[];

    $obj->$firstDayOfYear = date('Y-m-d', strtotime('first day of january ' . $year));
    $obj->$lastDayOfYear = date('Y-m-d', strtotime('last day of december ' . $year));

    $array[$year] = $obj;
}

var_dump($array);
  •  Tags:  
  • php
  • Related