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 ?
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.
You also need to return find_next_day();
....
} else {
return find_next_day($result,$days_array);
}
....
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
).