-1

I think I need some explanations about the recursivity... I looked at some same issues over forums but it didn't help me a lot.

Here is my function :

public function tas ($nb_gift, array $winners)
{
    if ( !empty( $nb_gift ) ){
        $id_winner = rand( 10, 15 );
        if ( !$this->_in_array_r($id_winner, $winners) ){
            $existing_user = $this->getWinner( $id_winner );    
        }
        if( !empty( $existing_user ) && $nb_gift > 0 ){
            $winners[] = array( $existing_user, 'iphone5');
            $this->tas($nb_gift - 1, $winners);
        }
        else {
            if($nb_gift > 0)
            {
                $this->tas($nb_gift, $winners);
            }
        }
    } 
    else {
        //print_r($winners);
        return $winners;
    }
}

At the end I have an array composed of the winners. Even if the print_r works, the return doesn't give me back my array. Does the function need some optimisation ?

Adrien G
  • 1,086
  • 2
  • 14
  • 32

1 Answers1

0

You are never returning anything from the first if branch. If you call tas() initially and it goes into the first if branch, it never returns, hence the caller is never getting anything back.

Recursion is nothing special, really. You call a function, you get a result:

$winners = tas();

Simple. Internally that functions may call other functions:

function tas() {
    return foo();
}

There's no restriction that tas can't call itself, but it's still bound by the same rules of returned data:

function tas() {
    if (...) {
        foo(); // <-- doesn't return anything
    } else {
        return foo();
    }
}

Just substitute foo() in the above example by tas() for the same concept, but including recursion.

deceze
  • 510,633
  • 85
  • 743
  • 889