1

I'm writing a code in PHP to find the next business day withing off days. This is my code:

function find_next_day($today,$days_array) {
    $day = new DateTime($today);
    $tomorrow = $day->modify('+1 day');
    $result = $tomorrow->format('Y-m-d');
    if (!in_array($result,$days_array)) {
        return $result;
    } else {
        find_next_day($result,$days_array);
    }
}

$off_days = array('2016-08-10','2016-08-25','2016-08-09','2016-08-11');
echo find_next_day('2016-08-09',$off_days); // I must get returned value as 2016-08-12

It's really strange that function does not return anything. But if I put echo $result before returning value in function, I can see the final result correctly!
What is my mistake here ?

Mohammad Saberi
  • 12,864
  • 27
  • 75
  • 127

3 Answers3

2

The problem is that you are not returning the result in the function in the else statement.

function find_next_day($today,$days_array) {
    $day = new DateTime($today);
    $tomorrow = $day->modify('+1 day');
    $result = $tomorrow->format('Y-m-d');
    if (!in_array($result,$days_array)) {
        return $result;
    } else {
        return find_next_day($result,$days_array);
    }
}

Try this one out. Should work.

Mohammad Saberi
  • 12,864
  • 27
  • 75
  • 127
twodee
  • 606
  • 5
  • 24
  • Thank you @CoderDude for your fast assistance. – Mohammad Saberi Aug 09 '16 at 19:54
  • @MohammadSaberi you should also make sure there's a default return value and not encapsulating them in `if else`s. If your problem was solved, you can accept the answer as a solution. – twodee Aug 09 '16 at 19:57
1

You also need to return find_next_day();

....
} else {
    return find_next_day($result,$days_array);
}
....
baao
  • 71,625
  • 17
  • 143
  • 203
0

The answers saying you should return find_next_day(...) are correct. However, you don't need a recursive function here. Recursive algorithms are for traversing branching/nested hierarchies where you don't know how deep the branching/nesting goes. In this case, you just want to evaluate a linear series of dates.

I recommend you use a simple while loop to check each date to see if it is a day off (maybe with a limit of 365 increments to $day).

Juan Tomas
  • 4,905
  • 3
  • 14
  • 19