phparraysvariableswarningsundefined-index

"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP


I'm running a PHP script and continue to receive errors like:

Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10

Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11

Warning: Undefined array key "my_index" in C:\wamp\www\mypath\index.php on line 11

Line 10 and 11 looks like this:

echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];

What is the meaning of these error messages?

Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.

How do I fix them?


This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.

Related Meta discussion:


Solution

  • This error message is meant to help a PHP programmer to spot a typo or a mistake when accessing a variable (or an array element) that doesn't exist. So a good programmer:

    1. Makes sure that every variable or array key is already defined by the time it's going to be used. In case a variable is needed to be used inside a function, it must be passed to that function as a parameter.
    2. Pays attention to this error and proceeds to fix it, just like with any other error. It may indicate a spelling error or that some procedure didn't return the data it should.
    3. Only on a rare occasion, when things are not under the programmer's control, a code can be added to circumvent this error. But by no means it should be a mindless habit.

    Notice / Warning: Undefined variable

    Although PHP does not require a 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 will be used later in the script. What PHP does in the case of undeclared variables is issue an error of E_WARNING level.

    This warning helps a programmer to spot a misspelled variable name or a similar kind of mistake (like a variable was assigned a value inside of a condition that evaluated to false). Besides, there are other possible issues with uninitialized variables. As it's stated in the PHP manual,

    Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name.

    Which means that a variable may get a value from the included file, and this value will be used instead of null that one expects accessing a non-initialized variable, which may lead to unpredictable results. To avoid that, all variables in a PHP file are best to be initialized before use.

    Ways to deal with the issue:

    1. Recommended: Declare every variable before use. This way you will see this error only when you actually make a mistake, trying to use a non-existent variable - the very reason this error message exists.

       //Initializing a variable
       $value = ""; //Initialization value; 0 for int, [] for array, etc.
       echo $value; // no error
       echo $vaule; // an error pinpoints a misspelled variable name
      
    1. Suppress the error with null coalescing operator. But remember that this way PHP won't be able to notify you about using wrong variable name.

       // Null coalescing operator
       echo $value ?? '';
      

      For the ancient PHP versions (< 7.0) isset() with ternary can be used

       echo isset($value) ? $value : '';
      

      Be aware though, that it's still essentially an error suppression, though for just one particular error. So it may prevent PHP from helping you by marking an unitialized variable.

    2. Suppress the error with the @ operator. Left here for the historical reasons but seriously, it just shouldn't happen.

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

    Notice: Undefined index / Undefined offset / Warning: Undefined array key

    This notice/warning appears when you (or PHP) try to access an undefined index of an array.

    Internal arrays

    When dealing with internal arrays, that are defined in your code, the attitude should be exactly the same: just initialize all keys before use. this way this error will do its intended job: notify a programmer about a mistake in their code. So the approach is the same:

    Recommended: Declare your array elements:

        //Initializing a variable
        $array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
        echo $array['value']; // no error
        echo $array['vaule']; // an error indicates a misspelled key
    

    A special case is when some function returns either an array or some other value such as null or false. Then it has to be tested before trying to access the array elements, such as

    $row = $stmt->fetch();
    if ($row) { // the record was found and can be worked with
        echo $row['name']; 
    }
    

    Outside arrays

    With outside arrays (such as $_POST / $_GET / $_SESSION or JSON input) the situation is a bit different, because programmer doesn't have the control over such arrays' contents. So checking for some key existence or even assigning a default value for a missing key could be justified.

    But assignments should be done at the very beginning of the script. Validate all input, assign it to local variables, and use them all the way in the code. So every variable you're going to access would deliberately exist.

    Related: