Skip to content
Advertisement

Value keeps overriding my old value in a session array

I have a very simple random number generator. This number generator has a few options: you input a minimum and maximum number, form this number a random number will be generated. I store the maximum-minimum and generated number inside of a session to be used later while playing the game.

When we get redirected to the main page (the guess game) you have the option to guess the random number that is stored in the session from their one forth the game will give you feedback on how close you are etc.

My question boils down to this, an option of the game is to display all your previous guesses I had a basic idea of how I wanted to do this: I will store the current guess I did inside of an array this array will be linked to a session from which I can loop through all of the old guesses.

I have written a couple of functions to achieve this and it only stores the current guess overriding any number already stored in the array e.g. if my current guess is 6 this number will be stored inside the array, if I proceed to guess again for example 4 this number will be stored inside of the array but will override 6.

I hope my code examples will be more clear.

this function stores the old guesses inside of said array

JavaScript

this function gets the current guess

JavaScript
JavaScript

I have a bunch of code examples should you need more

A few things you might need to know:

  • PHP = 7.4.2
  • The property $old_guesses is declared as an array like this public array $old_guesses;

Advertisement

Answer

You need to push onto the array, not assign to it.

JavaScript

The constructor should initialize the variable from the session variable to make it persist and grow.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement