Source Source - 5 months ago 16
PHP Question

php recursive function not working right

I am running a function, and part of it requires to pick a random number, however, it cannot be in an array of already selected numbers. So if the random number chosen is in the array, it needs to select a new number. I seem to be really struggling with something that seems so easy

function choice() {
global $countries;
global $count;
global $answers;
global $choice;
$i = rand(0,$count-1);
if(in_array($i,$answers)) choice();
else {
$answers[] = $i;
$choice = $countries[$i]['capital_city'];
return $choice;
}


So the current logic here, is it selects a random number, checks if its in the array, if it isnt then it sets the variable and returns it, if it is, then it generates a new number by restarting the function. What happens is when it does find one in the funtion, it returns an empty result, rather than going back through the function. What am I doing so wrong?

Answer

Add a return statement before the recursive call.

function choice() {
    global $countries;
    global $count;
    global $answers;
    global $choice;

    $i = rand(0,$count-1);

    if(in_array($i,$answers)) return choice();
    else {
        $answers[] = $i;
        $choice = $countries[$i]['capital_city'];
        return $choice;
    }