How can the use of $_SESSION variables be optimized in PHP scripts to avoid unnecessary duplication?

To optimize the use of $_SESSION variables in PHP scripts and avoid unnecessary duplication, you can store commonly used session variables in a single array within the $_SESSION superglobal. This helps reduce the number of individual session variables being set and accessed, improving code readability and maintainability.

// Initialize session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Store commonly used session variables in a single array
$_SESSION['user'] = [
    'id' => 123,
    'username' => 'john_doe',
    'email' => 'john.doe@example.com'
];

// Access the session variables using the array key
echo $_SESSION['user']['username'];