0

i did function for showing today date or next workday date, if is weekend. Function works great, but with return is something wrong.

$today = todayDate('2014-10-18'); // Saturday

    function todayDate($date) {
        if(date('N', strtotime($date)) >= 6) {
            echo 'If - ' . $date . '<br/>';
            $date = date('Y-m-d', strtotime('+1 day', strtotime($date)));
            todayDate($date);
        } else {
            echo 'Else - ' . $date . '<br/>';               
        }
        return $date;
    }

    echo '<br/><br/>Today: ' . $today . '<br/><br/>';

This function echoes following:

If - 2014-10-18
If - 2014-10-19
Else - 2014-10-20

But echo of $today (last row in code) is

Today: 2014-10-19

So, what is wrong? Last $date in function is "2014-10-20" and this value is returning to $today, but $today shows different value. Any idea?

2
  • 2
    The function is strictly speaking recursive, but you never assign the return value of the inner call to anything. Commented Oct 15, 2014 at 18:38
  • That code is hideously inefficient. You're doing repeated roundtrips from string->timestamp->string on every single call. Why don't you just pass the timestamp around and almost all of those strtotime calls? Commented Oct 15, 2014 at 18:52

1 Answer 1

1

As kojiro pointed out in the comment, you do not assign the return value of the inner call to todayDate(). To change this, replace this line

todayDate($date);

with

$date = todayDate($date);
Sign up to request clarification or add additional context in comments.

3 Comments

It works :-) I tought that function goes in this way todayDate(2014-10-18) > if > date+1 = 2014-10-19 > todayDate(2014-10-19) > if > date+1 = 2014-10-20 > todayDate(2014-10-20) > else > return --> last date value was 2014-10-20. $date = todayDate($date) goes out of my head, but important is, that it works. Thank you!
You should familiarize yourself with the concept of function return values. Recursive functions can lead to complicated errors.
Oh, today I looked at this function and ... I have it :-D Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.