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
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:
Its because the variable '$user_location' is not getting defined. If you are using any if loop inside which you are declaring the '$user_location' variable then you must also have an else loop and define the same. For example:
The above code will create error as The if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:
In PHP 7.0 it's now possible to use Null coalescing operator:
Equals to:
PHP manual PHP 7.0
I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.
My solution was this function:
So if I want to reference to $name and echo if exists, I simply write:
For array elements:
In page if I want to refer to $_REQUEST['name']:
I used to curse this error, but it can be helpful to remind you to escape user input.
For instance, if you thought this was clever, shorthand code:
...Think again! A better solution is:
(I use a custom
html()
function to escape characters, your mileage may vary)When dealing with files, a proper enctype and a POST method are required, which will trigger an undefined index notice if either are not included in the form.
The manual states the following basic syntax:
HTML
PHP
Reference:
Those notices are because you don't have the used variable
defined
andmy_index
key was not present into$my_array
variable.Those notices were triggered every time, because your
code
is not correct, but probably you didn't have the reporting of notices on.Solve the bugs:
Another way to get this out: