Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store the results of this recursive function?

Tags:

php

recursion

I have the following PHP code which works out the possible combinations from a set of arrays:

function showCombinations($string, $traits, $i){

    if($i >= count($traits)){

        echo trim($string) . '<br>';

    }else{

        foreach($traits[$i] as $trait){
            showCombinations("$string$trait", $traits, $i + 1);
        }

    }

}

$traits = array(
            array('1','2'),
            array('1','2','3'),
            array('1','2','3')
            );

showCombinations('', $traits, 0);

However, my problem is that I need to store the results in an array for processing later rather than just print them out but I can't see how this can be done without using a global variable.

Does anyone know of an alternative way to achieve something similar or modify this to give me results I can use?

like image 425
Tom Avatar asked Mar 01 '10 18:03

Tom


2 Answers

Return them. Make showCombinations() return a list of items. In the first case you only return one item, in the other recursive case you return a list with all the returned lists merged. For example:

function showCombinations(...) {
    $result = array();
    if (...) {
        $result[] = $item;
    }
    else {
        foreach (...) {
            $result = array_merge($result, showCombinations(...));
        }
    }
    return $result;
}
like image 162
Lukáš Lalinský Avatar answered Oct 31 '22 19:10

Lukáš Lalinský


In addition to the other answers, you could pass the address of an array around inside your function, but honestly this isn't nearly the best way to do it.

like image 38
agscala Avatar answered Oct 31 '22 20:10

agscala