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:
In PHP you need fist to define the variable after that you can use it.
We can check variable is defined or not in very efficient way!.
Simple Explanation
WHY IS THIS HAPPENING?
Over time, PHP has become a more security-focused language. Settings which used to be turned off by default are now turned on by default. A perfect example of this is
E_STRICT
, which became turned on by default as of PHP 5.4.0.Furthermore, according to PHP documentation, by default,
E_NOTICE
is disabled in php.ini. PHP docs recommend turning it on for debugging purposes. However, when I download PHP from the Ubuntu repository–and from BitNami's Windows stack–I see something else.Notice that
error_reporting
is actually set to the production value by default, not to the "default" value by default. This is somewhat confusing and is not documented outside of php.ini, so I have not validated this on other distributions.To answer your question, however, this error pops up now when it did not pop up before because:
You installed PHP and the new default settings are somewhat poorly documented but do not exclude
E_NOTICE
.E_NOTICE
warnings like undefined variables and undefined indexes actually help to make your code cleaner and safer. I can tell you that, years ago, keepingE_NOTICE
enabled forced me to declare my variables. It made it a LOT easier to learn C, were not declaring variables is much bigger of a nuisance.WHAT CAN I DO ABOUT IT?
Turn off
E_NOTICE
by copying the "Default value"E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
and replacing it with what is currently uncommented after the equals sign inerror_reporting =
. Restart Apache, or PHP if using CGI or FPM. Make sure you are editing the "right" php.ini. The correct one will be Apache if you are running PHP with Apache, fpm or php-fpm if running PHP-FPM, cgi if running PHP-CGI, etc. This is not the recommended method, but if you have legacy code that's going to be exceedingly difficult to edit, then it might be your best bet.Turn off
E_NOTICE
on the file or folder level. This might be preferable if you have some legacy code but want to do things the "right" way otherwise. To do this, you should consult Apache2, Nginx, or whatever your server of choice is. In Apache, you would usephp_value
inside of<Directory>
.Rewrite your code to be cleaner. If you need to do this while moving to a production environment or don't want someone to see your errors, make sure you are disabling any display of errors, and only logging your errors (see
display_errors
andlog_errors
in php.ini and your server settings).To expand on option 3: This is the ideal. If you can go this route, you should. If you are not going this route initially, consider moving this route eventually by testing your code in a development environment. While you're at it, get rid of
~E_STRICT
and~E_DEPRECATED
to see what might go wrong in the future. You're going to see a LOT of unfamiliar errors, but it's going to stop you from having any unpleasant problems when you need to upgrade PHP in the future.WHAT DO THE ERRORS MEAN?
Undefined variable: my_variable_name
- This occurs when a variable has not been defined before use. When the PHP script is executed, it internally just assumes a null value. However, in which scenario would you need to check a variable before it was defined? Ultimately, this is an argument for "sloppy code". As a developer, I can tell you that I love it when I see an open source project where variables are defined as high up in their scopes as they can be defined. It makes it easier to tell what variables are going to pop up in the future and makes it easier to read/learn the code.Undefined index: my_index
- This occurs when you try to access a value in an array and it does not exist. To prevent this error, perform a conditional check.Another option is to declare an empty array at the top of your function. This is not always possible.
(additional tip)
vim
person these days :).One common cause of a variable not existing after an HTML form has been submitted is the form element is not contained within a
<form>
tag:Example: Element not contained within the
<form>
Example: Element now contained within the
<form>
undefined index means in an array you requested for unavailable array index for example
undefined variable means you have used completely not existing variable or which is not defined or initialized by that name for example
undefined offset means in array you have asked for non existing key. And the solution for this is to check before use
Error display
@
operatorFor undesired and redundant notices, one could use the dedicated
@
operator to »hide« undefined variable/index messages.isset?:
or??
super-supression however. Notices still can get logged. And one may resurrect@
-hidden notices with:set_error_handler("var_dump");
if (isset($_POST["shubmit"]))
in your initial code.@
orisset
only after verifying functionality.@
is mainly acceptable for$_GET
/$_POST
input parameters, specifically if they're optional.And since this covers the majority of such questions, let's expand on the most common causes:
$_GET
/$_POST
/$_REQUEST
undefined inputFirst thing you do when encountering an undefined index/offset, is check for typos:
$count = $_GET["whatnow?"];
Secondly, if the notice doesn't have an obvious cause, use
var_dump
orprint_r
to verify all input arrays for their curent content:Both will reveal if your script was invoked with the right or any parameters at all.
Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:
POST parameters and GET input will be be shown separately.
For
$_GET
parameters you can also peek at theQUERY_STRING
inPHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well. You can also look at supplied raw
$_COOKIES
and other HTTP request headers that way.More obviously look at your browser address bar for GET parameters:
http://example.org/script.php?id=5&sort=desc
The
name=value
pairs after the?
question mark are your query (GET) parameters. Thus this URL could only possibly yield$_GET["id"]
and$_GET["sort"]
.Finally check your
<form>
and<input>
declarations, if you expect a parameter but receive none.<input name=FOO>
id=
ortitle=
attribute does not suffice.method=POST
form ought to populate$_POST
.method=GET
(or leaving it out) would yield$_GET
variables.action=script.php?get=param
via $_GET and the remainingmethod=POST
fields in $_POST alongside.$_REQUEST['vars']
again, which mashes GET and POST params.If you are employing mod_rewrite, then you should check both the
access.log
as well as enable theRewriteLog
to figure out absent parameters.$_FILES
$_FILES["formname"]
.enctype=multipart/form-data
method=POST
in your<form>
declaration.$_COOKIE
$_COOKIE
array is never populated right aftersetcookie()
, but only on any followup HTTP request.In a very Simple Language.
The mistake is you are using a variable
$user_location
which is not defined by you earlier and it doesn't have any value So I recommend you to please declare this variable before using it, For Example:$user_location = '';
Or
$user_location = 'Los Angles';
This is a very common error you can face.So don't worry just declare the variable and Enjoy Coding.