Filling arrays using a recursive function?

0

I have a recursive function that divides a certain number into parts, example: Number 259, when going through the function it will look like this: 200 and 59, I need to store these numbers in a array .

Example:

In the first loop of the loop you need to store the number 200 in the first position of the array and so on with all others

Function Code:

function ValorFinalArray($soma) 
{
    $tam = 0;
    do 
    {
        $tam = strlen($soma);
        if ($soma > 100 && $soma < 200) 
        {
            echo "cento <br/> e <br/>";
            echo substr($soma, -2);
            break;
        }
        $valor = $tam == 2 ? $soma : substr($soma, 0, $tam - ($tam - 1)) . str_repeat("0", $tam - ($tam - ($tam - 1)));

        if ($soma == "0")
            break;

        echo "<br/>numero: " . $valor . "<br />";

        if ($tam <= 2)
            break;

        echo "<br/> e "."<br />";

        $soma = $soma - $valor;
        $tam++;
    }
    while ($tam > 1);
}

echo ValorFinalArray(259);

return should look like this: array([0]=>200, [1]=> 59)

I need help with how I can do this process.

    
asked by anonymous 07.08.2017 / 21:07

1 answer

0

Just get the generated values and insert into a array in case a $ret variable of type array was created and the values generated, added in that array and at the end of that function, gives a return $ret , example :

function ValorFinalArray($soma) 
{
    $ret = array();
    $tam = 0;
    do 
    {
        $tam = strlen($soma);
        if ($soma > 100 && $soma < 200) 
        {
            echo "cento <br/> e <br/>";
            echo substr($soma, -2);
            break;
        }
        $valor = $tam == 2 ? 
           $soma : 
           substr($soma, 0, $tam - ($tam - 1)) . 
           str_repeat("0", $tam - ($tam - ($tam - 1)));

        if ($soma == "0")
            break;

        $ret[] = (int)$valor;

        if ($tam <= 2)
            break;

        $soma = $soma - $valor;
        $tam++;
    }
    while ($tam > 1);
    return $ret;
}

var_dump ( ValorFinalArray(259) );

I think your code will only serve this specific number, but I did not take into account what this function would generate, but I have demonstrated how that return can be done in array .

Online Example

    
07.08.2017 / 21:23