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:
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:
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:
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
a special case when a variable is defined but is not visible in a function. Functions in PHP have own variable scope, and if you need to use in a function a variable from outside, its value must be passed as a function's parameter:
function test($param) {
return $param + 1;
}
$var = 0;
echo test($var); // now $var's value is accessible inside through $param
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.
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.
This notice/warning appears when you (or PHP) try to access an undefined index of an array.
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'];
}
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.
when a PHP script contains an HTML form, it is natural that on the first load there is no form contents. Therefore such a script should check if a form was submitted
// for POST forms check the request method
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// process the form
}
// for GET forms / links check the important field
if (isset($_GET['search'])) {
// process the form
}
some HTML form elements, such as checkboxes, aren't sent to the server if not checked. In this case it is justified to use a null coalescing operator to assign a default value
$agreed = $_POST['terms'] ?? false;
optional QUERY STRING elements or cookies should be treated the same way
$limit = $_GET['limit'] ?? 20;
$theme = $_COOKIE['theme'] ?? 'light';
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: