What is the correct way to assign and retrieve session variables in PHP to avoid "undefined index" errors?

When assigning and retrieving session variables in PHP, it is important to first check if the session variable is set before trying to access it to avoid "undefined index" errors. This can be done using the isset() function. By checking if the session variable is set before accessing it, you can prevent PHP from throwing an error if the variable does not exist in the session.

// Assigning session variable
if(isset($_SESSION['username'])){
    $username = $_SESSION['username'];
} else {
    $username = "";
}

// Retrieving session variable
if(isset($_SESSION['user_id'])){
    $user_id = $_SESSION['user_id'];
} else {
    $user_id = "";
}