0

Have some issue with returning a value in recursive function. But I can echo it. What could be wrong with this?

function calculate($i,$count=1)
{
    $str_i = (string)$i;
    $rslt = 1;

    for ($k=0; $k<strlen($str_i); $k++) {
        $rslt = $str_i[$k]*$rslt;
    }

    if ( strlen((string)$rslt) > 1 ) {
        $this->calculate($rslt,++$count);
    } elseif ( strlen((string)$rslt) == 1 ) {
        return $count;  
    }
}
Alliswell
  • 1,425
  • 19
  • 34
  • What is the goal of this function? Can you please provide a test input? If `strlen((string)$rslt) == 0` the return is never reached. – A.L Dec 06 '14 at 01:24
  • Thanks for your response! This function calculate the Gardner's number! – Alliswell Dec 06 '14 at 10:06

1 Answers1

1

In the if in you code the value returned in the recursive call is not used. You don't set it to a value or return it. Thus every call except the base case doesn't return a value.

Try this:

function calculate($i,$count=1)
{
    $str_i = (string)$i;
    $rslt = 1;

    for ($k=0; $k<strlen($str_i); $k++) {
        $rslt = $str_i[$k]*$rslt;
    }

    if ( strlen((string)$rslt) > 1 ) {
        return $this->calculate($rslt,$count+1); // I changed this line
    } elseif ( strlen((string)$rslt) == 1 ) {
        return $count;  
    }
}

Now we return the value returned by the recursive call. Note I changed ++$count to $count+1 since it's bad style to mutate when using recursion.

Sylwester
  • 46,362
  • 4
  • 44
  • 75
  • Yea, it works! Thanks man, you rock!! Sorry, can't vote your answer up because of my low rating( Thank you one more time!! – Alliswell Dec 06 '14 at 09:04
  • @Alliswell You're welcome. If you find the answer useful consider [accepting the answer](http://meta.stackexchange.com/a/5235/232765) – Sylwester Dec 06 '14 at 12:38