0

I am new to coding and I'm trying to learn PHP by making a Tic Tac Toe game.

The PHP below is an attempt to make the server place an "O" in random in an empty slot each submit.

$empties = array();
$gameBoard = array();
$rand = 1;
for ($i = 0; $i < 9; $i++) {
    $gameBoard[$i] = "";
}

if (isset($_POST['gameBoard'])) {

    $gameBoard = $_POST['gameBoard'];

    for ($i = 0; $i < 9; $i++) {
        if ($gameBoard[$rand] !== 'X' and $gameBoard[$rand] !== 'O') {
            $gameBoard[$rand] = 'O';
            break;
        }
        $rand = rand(1, 9);
    }

However it does ,on random,work for a while and then throws undefined offset error or does not place an "O" at all.

This is the full code: http://phpfiddle.org/main/code/wza8-3niu

Your help is most appreciated.

Avi E. Koenig
  • 360
  • 5
  • 13
  • You do realize that you overwrite `$gameBoard` with _what ever_ the client posts in your conditional block? Why do you expect `$gameBoard[...]` to always exist then? – arkascha Jul 01 '17 at 15:20
  • This requires debugging on your end. Accessing an array index that is not set gives you that warning. Take a look when that happens, to do that, check if the index exists before you access it. The solution is in the end to only use existing indexes. – hakre Jul 01 '17 at 15:20
  • May I ask how this question is a duplicate? Also...my array is set to ="" on all its indexes by the for loop as far as I can understand. P.s. I'm new to coding and obviously make rudimentary mistakes. – Avi E. Koenig Jul 01 '17 at 15:54

1 Answers1

0

NVM I fixed it thanks anyway :)

  for ($i = 0; $i < 9; $i++) {
        $rand = rand(1, 9);
        if ($gameBoard[$rand] !== 'X' and $gameBoard[$rand] !== 'O') {
            $gameBoard[$rand] = 'O';
            break;
        }
    }
Avi E. Koenig
  • 360
  • 5
  • 13