Search code examples
phpdatefor-looptimeout

php timeout on for loop with dates


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);

Solution

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