How can undefined index errors be avoided when retrieving form data in PHP?

Undefined index errors can be avoided when retrieving form data in PHP by checking if the index exists in the $_POST or $_GET superglobals before trying to access it. This can be done using the isset() function to prevent PHP from throwing an error when the index does not exist. Example PHP code snippet:

if(isset($_POST['username'])) {
    $username = $_POST['username'];
} else {
    $username = "";
}

if(isset($_POST['email'])) {
    $email = $_POST['email'];
} else {
    $email = "";
}