0

I am making a number guessing game, where the person guesses different numbers until they guess the correct number, I want to record these different guesses into an array using the same variable but it only records the most recent guess, is there a way so that it records all guesses in this array?

    if (session_status() === PHP_SESSION_NONE) {
      session_start();
    }
    $_SESSION['incorrect'] = array();

    if(isset($_POST['submit'])){
      if(1 <= $_POST['guess'] && $_POST['guess'] <= 100){
        $guess = $_POST['guess'];
        if($guess < $number){
            echo "Your Number is Too Low";
            $_SESSION['guesses']++;
            array_push($_SESSION['incorrect'], $guess);
        } elseif($guess > $number){
            echo "Your Number is Too High";
            $_SESSION['guesses']++;
            array_push($_SESSION['incorrect'], $guess);
        } else {
            echo "Good Job <br>";
            echo $_SESSION['guesses']. "<br>";
            print_r($_SESSION['incorrect']);       
        }
      }else {
        echo "Please Enter a Number Between 1 and 100";
      }
    }
1
  • Try removing the if statement around session_start. Haven’t used sessions in awhile but i think you have to call that every time... Commented May 21, 2020 at 5:03

1 Answer 1

1

I think the problem is you’re setting the incorrect array to an empty array every time the page is loaded.

Fix it by changing the part where you set the incorrect array to:

if (!isset($_SESSION[“incorrect”])){

$_SESSION[“incorrect”] = array();

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.