1

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 it’s in the array. If it isn’t then it sets the variable and returns it. If it is, then it generates a new number by restarting the function. When it does find one in the function, it returns an empty result, rather than going back through the function. What am I doing so wrong?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Source
  • 1,026
  • 4
  • 11
  • 23

2 Answers2

2

If you don’t need to use recursion, you could just use a while loop:

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

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

    while (in_array($i, $answers)) {
        $i = rand(0, $count - 1);
    }

    $answers[] = $i;
    $choice = $countries[$i]['capital_city'];
    return $choice;
}

Or use this do while in place of the while;

do {
    $i = rand(0, $count-1);
} while (in_array($i, $answers));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
atoms
  • 2,993
  • 2
  • 22
  • 43
2

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;
    }
Rizier123
  • 58,877
  • 16
  • 101
  • 156