Mohammad Saberi Mohammad Saberi - 3 months ago 11
PHP Question

PHP function shows result but does not return it

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 ?

Answer

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.