Undefined index with PHP sessions

The reason for these errors is that you’re trying to read an array key that doesn’t exist. The isset() function is there so you can test for this. Something like the following for each element will work a treat; there’s no need for null checks as you never assign null to an element:

// check that the 'registered' key exists
if (isset($_SESSION['registered'])) {

    // it does; output the message
    echo $_SESSION['registered'];

    // remove the key so we don't keep outputting the message
    unset($_SESSION['registered']);
}

You could also use it in a loop:

$keys = array('registered', 'badlogin', 'neverused');

//iterate over the keys to test
foreach($keys as $key) {

    // test if $key exists in the $_SESSION global array
    if (isset($_SESSION[$key])) {

        // it does; output the value
        echo $_SESSION[$key];

        // remove the key so we don't keep outputting the message
        unset($_SESSION[$key]);
    }
}

Leave a Comment