2010-11-23 21:26:54 8 Comments
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:
Related Questions
Sponsored Content
32 Answered Questions
34 Answered Questions
18 Answered Questions
28 Answered Questions
[SOLVED] How can I prevent SQL injection in PHP?
- 2008-09-12 23:55:00
- Andrew G. Johnson
- 1529245 View
- 2779 Score
- 28 Answer
- Tags: php mysql sql security sql-injection
14 Answered Questions
[SOLVED] How to insert an item into an array at a specific index (JavaScript)?
- 2009-02-25 14:29:30
- tags2k
- 1434123 View
- 2345 Score
- 14 Answer
- Tags: javascript jquery arrays insert
23 Answered Questions
[SOLVED] How do you check if a variable is an array in JavaScript?
- 2009-04-20 09:02:59
- Andy McCluggage
- 876700 View
- 1608 Score
- 23 Answer
- Tags: javascript arrays variables
23 Answered Questions
[SOLVED] How to determine if variable is 'undefined' or 'null'?
- 2010-04-15 18:12:16
- sadmicrowave
- 2140122 View
- 1777 Score
- 23 Answer
- Tags: javascript jquery variables null undefined
15 Answered Questions
25 Answered Questions
[SOLVED] What is the scope of variables in JavaScript?
- 2009-02-01 08:27:19
- lYriCAlsSH
- 456826 View
- 1820 Score
- 25 Answer
- Tags: javascript function variables scope var
1 Answered Questions
[SOLVED] what is undefined index error in php?
- 2013-09-30 20:36:46
- user2832607
- 521 View
- -4 Score
- 1 Answer
- Tags: php undefined-index
27 comments
@Jaime Montoya 2018-09-01 18:31:57
I asked a question about this and I was referred to this post with the message:
I am sharing my question and solution here:
This is the error:
Line 154 is the problem. This is what I have in line 154:
I think the problem is that I am writing if conditions for the variable
$city
, which is not the key but the value in$key => $city
. First, could you confirm if that is the cause of the warning? Second, if that is the problem, why is it that I cannot write a condition based on the value? Does it have to be with the key that I need to write the condition?UPDATE 1: The problem is that when executing
$citiesCounterArray[$key]
, sometimes the$key
corresponds to a key that does not exist in the$citiesCounterArray
array, but that is not always the case based on the data of my loop. What I need is to set a condition so that if$key
exists in the array, then run the code, otherwise, skip it.UPDATE 2: This is how I fixed it by using
array_key_exists()
:@mario 2010-11-23 21:40:48
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.@Gajus 2014-02-11 12:24:04
If you are curious what is the performance impact, this article summarises it well, derickrethans.nl/….
@mario 2014-02-11 12:37:27
@GajusKuizinas There have been quoite a few changes since 2009, in particular php.net/ChangeLog-5.php#5.4.0 changes the outcome drastically (see "Zend Engine, performance" and "(silence) operator").
@Gajus 2014-02-11 16:30:07
Thanks @mario, interesting. Now, if someone was good enough to benchmark the two... 3v4l.org/CYVOn/perf#tabs 3v4l.org/FLp3D/perf#tabs According to this test, seem to be identical (notice that scale changes).
@Brynner Ferreira 2014-10-03 17:43:43
I tested with PHP 5.4 and the performance still bad.
@James 2018-07-06 18:56:38
Using a ternary is simple, readable, and clean:
Pre PHP 7
Assign a variable to the value of another variable if it's set, else assign
null
(or whatever default value you need):PHP 7+
The same except using Null Coalescing Operator. There's no longer a need to call
isset()
as this is built in, and no need to provide the variable to return as it's assumed to return the value of the variable being checked:Both will stop the Notices from the OP question, and both are the exact equivalent of:
If you don't require setting a new variable then you can directly use the ternary's returned value, such as with
echo
, function arguments, etc:Echo:
Function:
The above will work just the same with arrays, including sessions etc, replacing the variable being checked with e.g.:
$_SESSION['checkMe']
or however many levels deep you need, e.g.:
$clients['personal']['address']['postcode']
Suppression:
It is possible to suppress the PHP Notices with
@
or reduce your error reporting level, but it does not fix the problem, it simply stops it being reported in the error log. This means that your code still tried to use a variable that was not set, which may or may not mean something doesn't work as intended - depending on how crucial the missing value is.You should really be checking for this issue and handling it appropriately, either serving a different message, or even just returning a null value for everything else to identify the precise state.
If you just care about the Notice not being in the error log, then as an option you could simply ignore the error log.
@John Conde 2018-07-05 20:46:04
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>
@Ish 2010-11-23 21:31:08
Try these
Or, as a quick and dirty solution:
Note about sessions:
When using sessions,
session_start();
is required to be placed inside all files using sessions.http://php.net/manual/en/features.sessions.php
@ahmd0 2014-10-04 05:39:20
If using
E_NOTICE
from thephp.ini
configuration file, doerror_reporting = (E_ALL & ~E_NOTICE)
@Script47 2018-06-25 10:43:28
This answer is being discussed on meta.
@Alin Purcaru 2010-11-23 21:36:14
Notice: Undefined variable
From the vast wisdom of the PHP Manual:
From PHP documentation:
This means that you could use only
empty()
to determine if the variable is set, and in addition it checks the variable against the following,0,"",null
.Example:
Test the above snippet in the 3v4l.org online PHP editor
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 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:
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:This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:
Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):
Disable E_NOTICE from reporting. A quick way to exclude just
E_NOTICE
is:Suppress the error with the @ operator.
Note: It's strongly recommended to implement just point 1.
Notice: Undefined index / Undefined offset
This notice appears when you (or PHP) try to access an undefined index of an array.
Ways to deal with the issue:
Check if the index exists before you access it. For this you can use
isset()
orarray_key_exists()
:The language construct
list()
may generate this when it attempts to access an array index that does not exist:Two variables are used to access two array elements, however there is only one array element, index
0
, so this will generate:$_POST
/$_GET
/$_SESSION
variableThe 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 withsession_start()
and that the index also exists.Also note that all 3 variables are superglobals and are uppercase.
Related:
@IMSoP 2013-10-24 20:00:28
@dieselpower44 A couple of thoughts: The "shut-up operator" (
@
) has some performance issues. Also, since it suppresses all errors within a particular scope, using it without care might mask messages you wish you'd seen.@Salman A 2014-09-13 08:09:54
Hiding the issues is NOT the way to deal with issues. Items #2...#4 can be used only on production servers, not in general.
@Alph.Dev 2014-10-11 14:14:22
Is it possible to shut-up the message inline (not in handler) when also a custom error handler is used?
$var = @$_GET['nonexisting'];
still causes notice..@forsvunnet 2015-02-09 13:38:50
Why is it recommended to use 1.
$value = isset($_POST['value']) ? $_POST['value'] : '';
instead of using 4.$value = @$_POST['value'];
?@Aycan Yaşıt 2015-08-06 09:58:38
@twistedpixel Those 4 ways are independent, that's not a 4-step guide. So if you've chosen to use way 4, that means you didn't implement first 3 ways, so you you didn't supress any errors yet.
@Mugoma J. Okomba 2016-05-12 07:35:46
Using isset() didn't work for me. But array_key_exists() and @ works
@Mohamad Rostami 2016-11-17 20:01:41
I don't recommend using isset() for arrays, e.g.
$str = '111';
, (I know it should be array)isset($str[0])
will return true. It's better off using array_key_exist() instead of isset()@ZenithS 2017-06-29 02:09:05
We can also use
$_REQUEST += ['my_index' => null, '...' => null];
to fulfill missing indexes before usages. In-case that you already know the index keys.@AjAX. 2018-04-03 12:49:42
“This means that you could use only empty() to determine if the variable is set, and in addition it checks the variable against the following, 0,"",null.” Is incomplete. It also checks against
"0"
.@AbraCadaver 2018-05-25 18:40:00
All variables need to be accessed in uppercase if they were defined in uppercase, not just superglobals.
@Manish Goswami 2018-05-17 02:43:09
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
@Erik 2010-11-23 21:31:48
Generally because of "bad programming", and a possibility for mistakes now or later.
if (isset($varname))
, before using it@user395760 2010-11-23 21:37:54
Please don't turn warnings off. In stricter languages, they often mean "there might be a bug, you better check this line twice" - in a language as permissive as PHP, they often means "this code is crap and propably riddled with bugs; I'll try to make some sense of it but you better fix this ASAP".
@Valentin Flachsel 2010-11-23 21:38:37
Although I agree with the first three points, #4 is simply wrong. Hiding a problem won't make it go away, and it might even cause more problems down the road.
@Pekka 웃 2010-11-23 21:40:29
@Freek absolutely true, but in some scenarios (Bought script, zero technical knowledge, need it running by tomorrow...) it's the duct-tape solution - really bad, that always needs emphasizing, but an option
@Erik 2010-11-23 22:26:03
Duct-tape is good ... sometimes. Historically warnings have been turned of in standard PHP-settings, but defult settings have become more strict. Too bad many go back to the old settings, so as not to annoy the customers.
@Andrei Todorut 2018-01-25 13:09:56
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:
@Funk Forty Niner 2017-07-24 16:11:08
Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.
I.e.:
Then trying to access more columns/rows inside a loop.
I.e.:
or in a
while
loop:Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.
Consult the followning Q&A's on Stack:
Are table names in MySQL case sensitive?
mysql case sensitive table names in queries
MySql - Case Sensitive issue of tables in different server
@Funk Forty Niner 2018-10-25 00:26:18
I have to wonder why this was downvoted also.
@Funk Forty Niner 2017-10-07 12:21:51
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:
@phvish 2017-08-30 09:08:24
Probably you were using old PHP version until and now upgraded PHP thats the reason it was working without any error till now from years. until PHP4 there was no error if you are using variable without defining it but as of PHP5 onwards it throws errors for codes like mentioned in question.
@John Conde 2017-05-18 17:15:24
If working with classes you need to make sure you reference member variables using
$this
:@Sinte 2017-01-27 08:00:46
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
@Lachezar Lechev 2016-12-13 13:34:57
In PHP 7.0 it's now possible to use Null coalescing operator:
Equals to:
PHP manual PHP 7.0
@OCDev 2017-09-24 13:17:26
Wow, this answer needs to be voted up more now that this is available in PHP 7. Wonderful solution!!!
@a coder 2018-02-23 20:04:40
This also works fine in if statements.
if (is_array($my_array['idontexist'] ?? '')) { dosomething(); }
@Lachezar Lechev 2018-02-26 01:20:56
Your code is actually a nice overlooked bug: ?? - only checks for
isset()
, if you passis_array()
- which is a boolean, unexpected behavior will follow.@smcjones 2016-11-28 23:01:31
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 defualt,
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, where 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 :).@Wouter de Winter 2016-11-28 19:31:39
Regarding this part of the question:
No definite answers but here are a some possible explanations of why settings can 'suddenly' change:
You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.
You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using
ini_set()
orerror_reporting()
(search for these in the code)You changed the webserver configuration (assuming apache here):
.htaccess
files and vhost configurations can also manipulate php settings.Usually notices don't get displayed / reported (see PHP manual) so it is possible that when setting up the server, the php.ini file could not be loaded for some reason (file permissions??) and you were on the default settings. Later on, the 'bug' has been solved (by accident) and now it CAN load the correct php.ini file with the error_reporting set to show notices.
@Robbie 2016-11-23 01:44:03
In reply to ""Why do they appear all of a sudden? I used to use this script for years and I've never had any problem."
It is very common for most sites to operate under the "default" error reporting of "Show all errors, but not 'notices' and 'deprecated'". This will be set in php.ini and apply to all sites on the server. This means that those "notices" used in the examples will be suppressed (hidden) while other errors, considered more critical, will be shown/recorded.
The other critical setting is the errors can be hidden (i.e.
display_errors
set to "off" or "syslog").What will have happened in this case is that either the
error_reporting
was changed to also show notices (as per examples) and/or that the settings were changed todisplay_errors
on screen (as opposed to suppressing them/logging them).Why have they changed?
The obvious/simplest answer is that someone adjusted either of these settings in php.ini, or an upgraded version of PHP is now using a different php.ini from before. That's the first place to look.
However it is also possible to override these settings in
and any of these could also have been changed.
There is also the added complication that the web server configuration can enable/disable .htaccess directives, so if you have directives in .htaccess that suddenly start/stop working then you need to check for that.
(.htconf / .htaccess assume you're running as apache. If running command line this won't apply; if running IIS or other webserver then you'll need to check those configs accordingly)
Summary
error_reporting
anddisplay_errors
php directives in php.ini has not changed, or that you're not using a different php.ini from before.error_reporting
anddisplay_errors
php directives in .htconf (or vhosts etc) have not changederror_reporting
anddisplay_errors
php directives in .htaccess have not changederror_reporting
anddisplay_errors
php directives have been set there.@Rishabh Seth 2015-12-18 11:06:24
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.
@rybo111 2015-07-28 19:12:50
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)@mpyw 2014-08-26 22:15:35
The best way for getting input string is:
This one-liner is almost equivalent to:
If you absolutely want string value, just like:
@Shahin Mammadzada 2014-05-12 19:02:26
the quick fix is to assign your variable to null at the top of your code
@Roger 2012-12-29 11:46:28
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:
@gts 2013-06-06 20:37:30
why not keep things simple?
@user2253362 2013-04-09 13:43:28
I use all time own useful function exst() which automatically declare variables.
Your code will be -
@Ferenci Zoltán László 2011-12-30 14:14:59
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']:
@skierpage 2012-06-19 22:14:12
Your ifexists() function doesn't work for me in PHP 5.3. The caller's variables are not available in the function's local scope (see Variable scope), unless they are Superglobals or you fiddle with $GLOBALS, so
$foo = "BABAR"; ifexists('foo');
will in general return null. (Italics are php.net chapters.)@gcb 2013-07-09 05:31:06
now you will get "hello from"... what's the point? just check the value
if( !empty($user) and !empty($location) ) echo "hello $user ..."
@DGM 2010-11-23 21:35:20
It means you are testing, evaluating, or printing a variable that you have not yet assigned anything to. It means you either have a typo, or you need to check that the variable was initialized to something first. Check your logic paths, it may be set in one path but not in another.