-1

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,523
  • 20
  • 35
  • 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
  • 47,942
  • 4
  • 47
  • 79
  • 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