0

I want to get an array of dates within a period. To do so I thought up a for loop (seems simple enough...) But when I run it even with for the dates of 1 month it times out.

This is my php:

        $startdate = '2018-01-31';
        $recurring = '2';


        switch($recurring) {
            case '1':
                $period = '+1 day';
                break;
            case '2':
                $period = '+1 week';
                break;
            case '3':
                $period = '+1 month';
                break;
            case '4':
                $period = '+3 months';
                break;
            case '5':
                $perion = '+1 year';
                break;
            default:
                $period = null;
                break;
        }

        $dates = [];

        if($period !== null) {
            for($date = $startdate; $date < strtotime('+1 month', $startdate); strtotime($period, $date)) {
                $dates[] = $date;
            }
        }

        echo json_encode($dates);
6
  • Where are you increasing $date in that loop? Commented Aug 9, 2018 at 21:06
  • strtotime($period, $date) $period has the increment Commented Aug 9, 2018 at 21:07
  • 1
    Check the documentation for strtotime. Does it modify the timestamp passed as its second argument? Commented Aug 9, 2018 at 21:09
  • Right... it doesn't (of course). Any idea how to approach this then? Commented Aug 9, 2018 at 21:11
  • 1
    I found it.. changing strtotime($period, $date) to $date = strtotime($period, $date) did the trick. Thanks! @Don'tPanic Commented Aug 9, 2018 at 21:12

1 Answer 1

1

Increasing $date with $date = strtotime($period, $date) in the increment part of the for loop should keep it from timing out, but there are a couple of other improvements that could be made.

First I'd recommend calculating your end date once before the loop to avoid extra strtotime calls each time it checks the continuation condition.

$end = strtotime("$startdate +1 month");

Then, set $date = strtotime($startdate) in the initialization part, or you'll get a date string instead of a timestamp as the first value in your $dates array.

for ($date = strtotime($startdate); $date < $end; $date = strtotime($period, $date)) {
    $dates[] = $date;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.