1

Can I reset period object in php <=5.3.3? I would like to use same period object some times in foreach

<?php

$start = new DateTime('2013-10-01');
$end = new DateTime('2013-10-02');
$period = new DatePeriod($start, new DateInterval('P1D'), $end);

foreach ($period as $p) {
    var_dump($p);
}

reset($period);

foreach ($period as $p) {
    var_dump($p);
}

Demo

Dmitry Teplyakov
  • 2,898
  • 5
  • 26
  • 46
  • The Demo should not be in the question since it provides the answer – Brewal Nov 18 '13 at 09:37
  • 2
    @Brewal Not really - If you look at the question (and not just the title which has a `>` instead of a `<`) then you'll see that the output for 5.3.0 - 5.3.3 is different than 5.3.4+. OP asks what to do in 5.3.0 - 5.3.3. – h2ooooooo Nov 18 '13 at 09:39
  • well, the ideal solution is to upgrade. The reason 5.3.4 exists is to fix issues that were in 5.3.3. The same applies with all subsequent versions through to 5.3.27. If you're still on 5.3.3, then you're a long way behind on your updates. – Spudley Nov 18 '13 at 09:56
  • @Spudley Not always we have control about production server ;) I need solution to work with any 5.3 version.. So Glavic's solution is well for me – Dmitry Teplyakov Nov 18 '13 at 12:31

1 Answers1

4

You can use function iterator_to_array()PHP >= 5.1.0, that copies elements of an iterator to array. Then you can use this array multiple times.

// ...
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
$periods = iterator_to_array($period);
// ...

Demo

Glavić
  • 42,781
  • 13
  • 77
  • 107