1

this is related to another question asked here, which works perfect but i need it in reverse, do you have any idea how to implement this?

original question here I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Community
  • 1
  • 1
Display name
  • 420
  • 5
  • 20

4 Answers4

4

You could use iterator_to_array + array_reverse methods:

foreach (array_reverse(iterator_to_array($period)) as $day) {...}
Im0rtality
  • 3,463
  • 3
  • 31
  • 41
1

This example loops reverse between dates and jumping by months. The last line in the WHILE loop allow to jump by any number of months, years, days...

$start = $month = strtotime("2023-07-01"); //You must use the same day date
$end = strtotime("2021-12-01");

while($month>=$end) { //use > if don't want the last month

  //Insert you code here

  echo date('M Y', $month) . " "; //just to show it works
  //the next line is the key. You can reverse jump by a month and PHP understand changes of year
  $month = mktime(0, 0, 0, date("m", $month)-1, date("d", $month), date("Y", $month) );
}
0

Using PHP 5.5 Generators

function period($begin, $interval, $end) {
    if ($begin < $end) {
        while ($begin <= $end) {
            yield $begin;
            $begin->add($interval);
        }
    }else {
        while ($end <= $begin) {
            yield $begin;
            $begin->sub($interval);
        }
    }
}

$interval = new \DateInterval('P1D');

$begin = new \DateTime( '2010-05-10' );
$end = new \DateTime( '2010-05-01' );

foreach (period($begin, $interval, $end) as $dt) {
    echo $dt->format( "l Y-m-d H:i:s" ), PHP_EOL;
}

$begin = new \DateTime( '2010-05-01' );
$end = new \DateTime( '2010-05-10' );

foreach (period($begin, $interval, $end) as $dt) {
    echo $dt->format( "l Y-m-d H:i:s" ), PHP_EOL;
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
-1

yes you can use it in a reverse of date format

$begin = new DateTime( '2010-05-01' );
$end   = new DateTime( '2010-05-10' );

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

$reverse = array_reverse(iterator_to_array($period));  //sorts in descending order...

foreach ( $reverse as $dt )
  echo $dt->format( "l Y-m-d H:i:s\n" ); //apply the format you want.

if i have got u wrong pls comment...

Ronser
  • 1,855
  • 6
  • 20
  • 38