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?

2

4 Answers 4

5

You could use iterator_to_array + array_reverse methods:

foreach (array_reverse(iterator_to_array($period)) as $day) {...}
1
  • perfect exactly what i was looking for. thank you. i have done the array reverse but missed the iterator_array. Oct 10, 2014 at 11:36
2

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;
}
-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...

2
  • You can't sort a DatePeriod object using the array functions.
    – cmbuckley
    Oct 10, 2014 at 11:43
  • sry, changed to array_reverse
    – Ronser
    Oct 10, 2014 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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