Jackie Robbins
Jackie Robbins

Reputation: 3

What do i need to do to "while loop" stop?

I want to check if the user enters a number between 1-10, if he does, the program should proceed, if not the program should prompt him to reenter. here's my code (php)

$good = false;
   while ($good == false){
   $guess = readline(">>");
   $guess = intval($guess);
   if($guess == 1 or $guess == 2 or $guess == 3 or $guess == 4 or $guess == 5 or $guess == 6 or $guess == 7 or $guess == 8 or $guess == 9 or $guess == 10){
     $guess = true;
   }else{
    echo "Invalid number. Please try again.\n";
     $guess == false; 
   }
     }

it continues to loop even if the user enter a number between 1-10. I've tried to debug with no success. any suggestions?

Upvotes: 0

Views: 49

Answers (1)

Aung
Aung

Reputation: 126

You are trying to update $guess instead of $good. According to your loop, $guess will never be updated to true and it will always be false. So, your loop will continue anyway.

You should update $good to false once your condition is met and this will stop the loop.

One more thing is you should use php in_array() function rather than comparing $guess variable against 1 to 10.

You should check like this:

    if (in_array($guess, [1,2,3,4,5,6,7,8,9,10])){
    // your code here
}

or even like this:

$accepted_numbers = array(1,2,3,4,5,6,7,8,9,10);

if (in_array($guess, $accepted_numbers)){
    // your code here
}

See code below:

$accepted_numbers = array(1,2,3,4,5,6,7,8,9,10);

    if (in_array($guess, $accepted_numbers)){
             // $guess = true;
             $good = true; // you should update $good to true

           }else{
            echo "Invalid number. Please try again.\n";
              // $guess == false; (you don't need this) 
           }

Upvotes: 1

Related Questions