1

I have a nested recursive function it's a task from codewars.

persistence(39) === 3; // because 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4 and 4 has only one digit persistence(999) === 4; // because 9 * 9 * 9 = 729, 7 * 2 * 9 = 126, 1 * 2 * 6 = 12, and finally 1 * 2 = 2; persistence(4) === 0; // because 4 is already a one-digit number

which throws :

Fatal error: Cannot redeclare rec();

function persistence(int $num): int {
    $str = (string)$num;
    $nums = str_split($str);
    $count = count($nums);

    if( $count === 0 ){
        return 0;
    }
    $x = 0;

    function rec($nums, $n) {

        $result = [];
        for ($i = 0; $i < count($nums); ++$i) {
            if ($i == 0) {
                $result = $nums[$i];
            } else {
                $result *= $nums[$i];
            }
        }

        $num = implode('',$nums);
        $diff = $num - $result;
        if ( $diff != 0 ) {
            $n += 1;
            $result = str_split($result,1);
            return rec($result, $n);
        }
        return $n;
    }

    $result = rec($nums,$x);



    return (int)$result;

}

I've tried to use an variable function

$rec = 'rec'; 
$result = $rec($nums,$n)

but there are another error : `

Fatal error: Cannot redeclare rec()

` PHP 7.4 version. Can anyone explain me what the problem is ?

Daniel
  • 21
  • 4
  • Show the calling code that you need to use, some test data and expected result. At least then I can try and get it to run. i.e. An example I can just run and play with. :) – Ryan Vincent Feb 05 '21 at 22:15

1 Answers1

2

Don't define the function inside the other function:

You have:

function persistence(int $num): int {
    // code ...
    function rec($nums, $n) {
        // code ...
    }
}

This means that the function rec should be created each time the function persistence gets called.

You should define them first:

function persistence(int $num): int {
    // code ...
}
function rec($nums, $n) {
    // code ...
}

And then call them to your liking, for example like you already do:

$rec = 'rec'; 
$result = $rec($nums,$n)
ArSeN
  • 5,133
  • 3
  • 19
  • 26
  • Thanks! But I am trying to solve the code wars kata. So this is a necessary decision. Are there other ways? – Daniel Feb 05 '21 at 21:21
  • Other ways for what exactly? Redefining the same function over and over will not help you in any way. If you are talking about recursion: This is about making **the calls** to the function recursive, not its definition/declaration. – ArSeN Feb 06 '21 at 00:11