How to store values of a recursive function in an array?

Asked

Viewed 1,427 times

3

I tried to pass an array as a parameter, but returned only the first counter value. What is the correct way to return an array with all the values inside in a recursive function? Follow the function with array return:

Follows the initial function:

function minhaFuncao($contador)
{
if($contador < 10)
{
    echo "O contador agora é: ".$contador."<br>";
    $contador++;
    minhaFuncao($contador);
}
    return true;
}

minhaFuncao(1);

Follow function with attempt to return with array:

function minhaFuncao($contador, $lista = array())
{
if($contador < 10)
{
    echo "O contador agora é: ".$contador."<br>";
    $lista[] = $contador;
    $contador++;
    minhaFuncao($contador);
}
    return $lista;
}

print_r(minhaFuncao(1));
  • 1

    If the answer below explained the problem and solved it may mark the answer as right...

1 answer

5


The problem is that you are not passing the array as parameter or returning the value of the recursive call.

You can do it like this:

function minhaFuncao($contador, $lista = array())
{
    if($contador < 10)
    {
        $lista[] = $contador;
        $contador++;
        return minhaFuncao($contador, $lista);
    }

    return $lista;
}
  • Perfect! Exactly what I was trying. I had thought that the array zeroed every time it was called inside the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.