phpfunctiondaterecursionweekend

Function recursive to get a day that don't be sunday or saturday


I have a problem with my function, what it does is, see if a date fell on Saturday or Sunday if so, add a day until the day is not Saturday not Sunday, it is supposed that it should return the correct date. For example, I am entering the date 2021-03-20 and it returns the date of 2021-03-21, when 2021-03-22 should return. I do not know what is happening here I leave my function:

enter code here

private function isWeekend($date) {
    // Convert string to time
    // Get day name from the date
    $dt2 = date("l", strtotime($date));
    // Convert day name to lower case
    $dt3 = strtolower($dt2);
    $date_ = $date;
    // Check if day name is "saturday" or "sunday"
        if(($dt3 == "saturday" ) || ($dt3 == "sunday")) {
            // If the date is weekend then
            $date_ = date('Y-m-d', strtotime($date."+ 1 days"));
            $this->isWeekend($date_);
        }
    return $date_;
}

Solution

  • You aren't capturing the value of the recursive call. Try this:

    return $this->isWeekend($date_);
    

    or

    $date_ = $this->isWeekend($date_);