How can you prevent the array from being overwritten when a button is clicked in a Tic-Tac-Toe game created with PHP?
To prevent the array from being overwritten when a button is clicked in a Tic-Tac-Toe game created with PHP, you can use sessions to store the game state. This way, the array will persist between page loads and button clicks. You can update the array in the session whenever a button is clicked, ensuring that the game state is maintained throughout the gameplay.
<?php
session_start();
// Initialize the game array if it doesn't exist
if (!isset($_SESSION['game'])) {
$_SESSION['game'] = [
['', '', ''],
['', '', ''],
['', '', '']
];
}
// Update the game array when a button is clicked
if (isset($_POST['row']) && isset($_POST['col']) && isset($_POST['player'])) {
$row = $_POST['row'];
$col = $_POST['col'];
$player = $_POST['player'];
$_SESSION['game'][$row][$col] = $player;
}
// Display the Tic-Tac-Toe board
echo '<table>';
for ($i = 0; $i < 3; $i++) {
echo '<tr>';
for ($j = 0; $j < 3; $j++) {
echo '<td>' . $_SESSION['game'][$i][$j] . '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
<form method="post">
<input type="hidden" name="row" value="0">
<input type="hidden" name="col" value="0">
<input type="hidden" name="player" value="X">
<button type="submit">Play X</button>
</form>
<!-- Repeat the form for other cells in the Tic-Tac-Toe board -->