PHP: “Notice: Undefined variable” and “Notice: Undefined index”

Although PHP does not require variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that he will use later in the script. What PHP does in the case of undeclared variables is issue a very low level error, E_NOTICE, one that is not even reported by default, but the Manual advises to allow during development.

Ways to deal with the issue:

  1. Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() / !empty() to check if they are declared before referencing them, as in:
    //Initializing variable
    $value = ""; //Initialization value; Examples
                 //"" When you want to append stuff later
                 //0  When you want to add numbers later
    //isset()
    $value = isset($_POST['value']) ? $_POST['value'] : '';
    //empty()
    $value = !empty($_POST['value']) ? $_POST['value'] : '';
  2. Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):
    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
  3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:
    error_reporting( error_reporting() & ~E_NOTICE )
  4. Suppress the error with the @ operator.

Note: It’s strongly recommended to implement just point 1.

Notice: Undefined index

This notice appears when you try to access an undefined index of an array.

Ways to deal with the issue:

  1. Check if the index exists before you access it. For this you can use isset() or array_key_exists():
    //isset()
    $value = isset($array['my_index']) ? $array['my_index'] : '';
    //array_key_exists()
    $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';

$_POST / $_GET / $_SESSION variable

The notices above appear often when working with $_POST, $_GET or $_SESSION. For $_POST and $_GET you just have to check if the index exists or not before you use them. For $_SESSION you have to make sure you have the session started with session_start() and that the index also exists.

Related:

(Visited 151 times, 1 visits today)
How can I get query string values in JavaScript?
How do I compare strings in Java?

Comments

comments

Leave a Reply

Your email address will not be published. Required fields are marked *