user784637
user784637

Reputation: 16102

Why do you need to include the "return" keyword in a recursive function?

I have the following function that implements division without the use of a modulus operator

function division($dividend, $divisor, $quotient){
    if($dividend<=$divisor){
        return $quotient;
    }else{
        $dividend-=$divisor;
        $quotient++;
        division($dividend, $divisor, $quotient);
    }
}

echo division(3, 2, 0);

I'm confused why I need to prepend the return keyword to the line division($dividend, $divisor, $quotient) if the function is going to iterate until the if statement evaluates to true and return $quotient evaluates.

Can someone explain why the return keyword is needed?

Upvotes: 0

Views: 78

Answers (1)

laurent
laurent

Reputation: 90756

This is because once the quotient has been calculated, you might want to do something with it. In your case you are displaying it with the echo statement. Without the return call, you cannot know what the result of the function is.

Upvotes: 1

Related Questions