How can PHP sessions be structured to prevent overwriting data when storing multiple values for the same variables?

To prevent overwriting data when storing multiple values for the same variables in PHP sessions, you can use arrays to store multiple values under a single session variable key. This way, each value will be stored as an element in the array, preventing data from being overwritten.

// Start the session
session_start();

// Check if the session variable is already an array, if not, initialize it as an empty array
if (!isset($_SESSION['my_variable']) || !is_array($_SESSION['my_variable'])) {
    $_SESSION['my_variable'] = array();
}

// Add a new value to the array under the session variable key
$_SESSION['my_variable'][] = 'new_value';