0

I have two dates and I would like to do a loop to display each day between thoses two dates.

Ex :

$begin=date("Y-m-d");
$end="2017-01-01";

I know how can I do with date in the past untill today, but I don't konw from today untill a date in the past. An idea ?

My script :

$today=date("Y-m-d");
$begin = new DateTime($today);
$end = new DateTime('2017-01-01');
$begin = $begin->modify( '-1 day' );
$interval = new DateInterval('P1D');
$period = new DatePeriod($begin, $interval, $end);



foreach ($period as $dt)
{
    $datedisplay=$dt->format("Ymd" );
    echo ''.$datedisplay.'<BR>';
}

Thank you !

Bisvan
  • 127
  • 1
  • 11
  • Do you mean that you want to reverse the looping direction of the `DatePeriod` iterator? You can't directly reverse an iterator but you can iterate over it once and then reverse the collected values using something like `array_reverse`. – Halcyon Apr 21 '17 at 12:57
  • Yes I would like to reverse the loop to display date from "today" to "yesterday" – Bisvan Apr 21 '17 at 12:58
  • Time doesn't move backwards ... – Narf Apr 21 '17 at 13:07

1 Answers1

0

Based on the solution found here : PHP: Return all dates between two dates in an array

You might want to do the following :

$today=date("Y-m-d", strtotime('-1 day')); // We remove oneday from today
$begin = $today;
$end = '2017-01-01';

function getDatesFromRange($a,$b,$x=0,$dates=[]){
    while(end($dates)!=$b && $x=array_push($dates,date("Y-m-d",strtotime("$a +$x day"))));
    return $dates;
}
$arrayDates = getDatesFromRange($end,$begin);
$reverseDates = array_reverse($arrayDates); // then we reverse array

var_dump($reverseDates);

This will give you a full array containing every day from yesterday to the wanted date.

Community
  • 1
  • 1
Nirnae
  • 1,315
  • 11
  • 23