“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP











up vote
998
down vote

favorite
207












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




Notice: Undefined variable: my_variable_name in C:wampwwwmypathindex.php on line 10



Notice: Undefined index: my_index C:wampwwwmypathindex.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:




  • What can be done about repetitive questions?

  • Do “reference questions” make sense?











share|improve this question




















  • 7




    possible duplicate of Reference - What does this error mean in PHP?
    – meagar
    Oct 8 '13 at 15:25






  • 2




    the variable might not have been initialized. Are you initializing the variable from a post or get or any array? If that's the case you might not have an field in that array. That your accessing.
    – Anish Silwal
    Dec 15 '15 at 13:12






  • 3




    @Pekka웃 - I noticed the edit adding the "and "Notice: Undefined offset"" - Wouldn't it make more sense using "PHP: “Undefined variable”, “Undefined index”, “Undefined offset” notices" (even take out the PHP, since it is tagged as "php". Plus, the URL gets cut off at and-notice-undef, just a suggestion so that the URL doesn't get cut off. Maybe even removing the (too many) quotes. Or PHP: “Undefined variable/index/offset” notices
    – Funk Forty Niner
    Jan 20 '17 at 15:24








  • 2




    @Fred I guess an argument can be made for both variations. THere's a chance that newbies will enter the entire line, including the "Notice:" into their search query, which I'm sure is the main traffic generator for this question. If the messages are there in full, that's likely to improve visibility in search engines
    – Pekka 웃
    Jan 20 '17 at 15:34








  • 2




    @Pekka웃 I understand. I only said that because the URL didn't get cut off before and now it does at and-notice-undef. It was just a (few) suggestion(s). It just repeats itself also being Notice: Undefined.
    – Funk Forty Niner
    Jan 20 '17 at 15:35

















up vote
998
down vote

favorite
207












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




Notice: Undefined variable: my_variable_name in C:wampwwwmypathindex.php on line 10



Notice: Undefined index: my_index C:wampwwwmypathindex.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:




  • What can be done about repetitive questions?

  • Do “reference questions” make sense?











share|improve this question




















  • 7




    possible duplicate of Reference - What does this error mean in PHP?
    – meagar
    Oct 8 '13 at 15:25






  • 2




    the variable might not have been initialized. Are you initializing the variable from a post or get or any array? If that's the case you might not have an field in that array. That your accessing.
    – Anish Silwal
    Dec 15 '15 at 13:12






  • 3




    @Pekka웃 - I noticed the edit adding the "and "Notice: Undefined offset"" - Wouldn't it make more sense using "PHP: “Undefined variable”, “Undefined index”, “Undefined offset” notices" (even take out the PHP, since it is tagged as "php". Plus, the URL gets cut off at and-notice-undef, just a suggestion so that the URL doesn't get cut off. Maybe even removing the (too many) quotes. Or PHP: “Undefined variable/index/offset” notices
    – Funk Forty Niner
    Jan 20 '17 at 15:24








  • 2




    @Fred I guess an argument can be made for both variations. THere's a chance that newbies will enter the entire line, including the "Notice:" into their search query, which I'm sure is the main traffic generator for this question. If the messages are there in full, that's likely to improve visibility in search engines
    – Pekka 웃
    Jan 20 '17 at 15:34








  • 2




    @Pekka웃 I understand. I only said that because the URL didn't get cut off before and now it does at and-notice-undef. It was just a (few) suggestion(s). It just repeats itself also being Notice: Undefined.
    – Funk Forty Niner
    Jan 20 '17 at 15:35















up vote
998
down vote

favorite
207









up vote
998
down vote

favorite
207






207





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




Notice: Undefined variable: my_variable_name in C:wampwwwmypathindex.php on line 10



Notice: Undefined index: my_index C:wampwwwmypathindex.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:




  • What can be done about repetitive questions?

  • Do “reference questions” make sense?











share|improve this question















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




Notice: Undefined variable: my_variable_name in C:wampwwwmypathindex.php on line 10



Notice: Undefined index: my_index C:wampwwwmypathindex.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:




  • What can be done about repetitive questions?

  • Do “reference questions” make sense?








php arrays variables warnings undefined-index






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 29 at 20:02


























community wiki





27 revs, 18 users 29%
Pekka 웃









  • 7




    possible duplicate of Reference - What does this error mean in PHP?
    – meagar
    Oct 8 '13 at 15:25






  • 2




    the variable might not have been initialized. Are you initializing the variable from a post or get or any array? If that's the case you might not have an field in that array. That your accessing.
    – Anish Silwal
    Dec 15 '15 at 13:12






  • 3




    @Pekka웃 - I noticed the edit adding the "and "Notice: Undefined offset"" - Wouldn't it make more sense using "PHP: “Undefined variable”, “Undefined index”, “Undefined offset” notices" (even take out the PHP, since it is tagged as "php". Plus, the URL gets cut off at and-notice-undef, just a suggestion so that the URL doesn't get cut off. Maybe even removing the (too many) quotes. Or PHP: “Undefined variable/index/offset” notices
    – Funk Forty Niner
    Jan 20 '17 at 15:24








  • 2




    @Fred I guess an argument can be made for both variations. THere's a chance that newbies will enter the entire line, including the "Notice:" into their search query, which I'm sure is the main traffic generator for this question. If the messages are there in full, that's likely to improve visibility in search engines
    – Pekka 웃
    Jan 20 '17 at 15:34








  • 2




    @Pekka웃 I understand. I only said that because the URL didn't get cut off before and now it does at and-notice-undef. It was just a (few) suggestion(s). It just repeats itself also being Notice: Undefined.
    – Funk Forty Niner
    Jan 20 '17 at 15:35
















  • 7




    possible duplicate of Reference - What does this error mean in PHP?
    – meagar
    Oct 8 '13 at 15:25






  • 2




    the variable might not have been initialized. Are you initializing the variable from a post or get or any array? If that's the case you might not have an field in that array. That your accessing.
    – Anish Silwal
    Dec 15 '15 at 13:12






  • 3




    @Pekka웃 - I noticed the edit adding the "and "Notice: Undefined offset"" - Wouldn't it make more sense using "PHP: “Undefined variable”, “Undefined index”, “Undefined offset” notices" (even take out the PHP, since it is tagged as "php". Plus, the URL gets cut off at and-notice-undef, just a suggestion so that the URL doesn't get cut off. Maybe even removing the (too many) quotes. Or PHP: “Undefined variable/index/offset” notices
    – Funk Forty Niner
    Jan 20 '17 at 15:24








  • 2




    @Fred I guess an argument can be made for both variations. THere's a chance that newbies will enter the entire line, including the "Notice:" into their search query, which I'm sure is the main traffic generator for this question. If the messages are there in full, that's likely to improve visibility in search engines
    – Pekka 웃
    Jan 20 '17 at 15:34








  • 2




    @Pekka웃 I understand. I only said that because the URL didn't get cut off before and now it does at and-notice-undef. It was just a (few) suggestion(s). It just repeats itself also being Notice: Undefined.
    – Funk Forty Niner
    Jan 20 '17 at 15:35










7




7




possible duplicate of Reference - What does this error mean in PHP?
– meagar
Oct 8 '13 at 15:25




possible duplicate of Reference - What does this error mean in PHP?
– meagar
Oct 8 '13 at 15:25




2




2




the variable might not have been initialized. Are you initializing the variable from a post or get or any array? If that's the case you might not have an field in that array. That your accessing.
– Anish Silwal
Dec 15 '15 at 13:12




the variable might not have been initialized. Are you initializing the variable from a post or get or any array? If that's the case you might not have an field in that array. That your accessing.
– Anish Silwal
Dec 15 '15 at 13:12




3




3




@Pekka웃 - I noticed the edit adding the "and "Notice: Undefined offset"" - Wouldn't it make more sense using "PHP: “Undefined variable”, “Undefined index”, “Undefined offset” notices" (even take out the PHP, since it is tagged as "php". Plus, the URL gets cut off at and-notice-undef, just a suggestion so that the URL doesn't get cut off. Maybe even removing the (too many) quotes. Or PHP: “Undefined variable/index/offset” notices
– Funk Forty Niner
Jan 20 '17 at 15:24






@Pekka웃 - I noticed the edit adding the "and "Notice: Undefined offset"" - Wouldn't it make more sense using "PHP: “Undefined variable”, “Undefined index”, “Undefined offset” notices" (even take out the PHP, since it is tagged as "php". Plus, the URL gets cut off at and-notice-undef, just a suggestion so that the URL doesn't get cut off. Maybe even removing the (too many) quotes. Or PHP: “Undefined variable/index/offset” notices
– Funk Forty Niner
Jan 20 '17 at 15:24






2




2




@Fred I guess an argument can be made for both variations. THere's a chance that newbies will enter the entire line, including the "Notice:" into their search query, which I'm sure is the main traffic generator for this question. If the messages are there in full, that's likely to improve visibility in search engines
– Pekka 웃
Jan 20 '17 at 15:34






@Fred I guess an argument can be made for both variations. THere's a chance that newbies will enter the entire line, including the "Notice:" into their search query, which I'm sure is the main traffic generator for this question. If the messages are there in full, that's likely to improve visibility in search engines
– Pekka 웃
Jan 20 '17 at 15:34






2




2




@Pekka웃 I understand. I only said that because the URL didn't get cut off before and now it does at and-notice-undef. It was just a (few) suggestion(s). It just repeats itself also being Notice: Undefined.
– Funk Forty Niner
Jan 20 '17 at 15:35






@Pekka웃 I understand. I only said that because the URL didn't get cut off before and now it does at and-notice-undef. It was just a (few) suggestion(s). It just repeats itself also being Notice: Undefined.
– Funk Forty Niner
Jan 20 '17 at 15:35














28 Answers
28






active

oldest

votes

















up vote
918
down vote



accepted










Notice: Undefined variable



From the vast wisdom of 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. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.




From PHP documentation:




No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false
.




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:






$o = ;
@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var, function($v) {
echo (!isset($v) || $v == false) ? 'true ' : 'false';
echo ' ' . (empty($v) ? 'true' : 'false');
echo "n";
});


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:





  1. 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:



    //Initializing variable
    $value = ""; //Initialization value; Examples
    //"" When you want to append stuff later
    //0 When you want to add numbers later
    //isset()
    $value = isset($_POST['value']) ? $_POST['value'] : '';
    //empty()
    $value = !empty($_POST['value']) ? $_POST['value'] : '';


    This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:



    // Null coalesce operator - No need to explicitly initialize the variable.
    $value = $_POST['value'] ?? '';



  2. Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):



    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)



  3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:



    error_reporting( error_reporting() & ~E_NOTICE )


  4. 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:





  1. Check if the index exists before you access it. For this you can use isset() or array_key_exists():



    //isset()
    $value = isset($array['my_index']) ? $array['my_index'] : '';
    //array_key_exists()
    $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';



  2. The language construct list() may generate this when it attempts to access an array index that does not exist:



    list($a, $b) = array(0 => 'a');
    //or
    list($one, $two) = explode(',', 'test string');



Two variables are used to access two array elements, however there is only one array element, index 0, so this will generate:




Notice: Undefined offset: 1





$_POST / $_GET / $_SESSION variable



The 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 with session_start() and that the index also exists.



Also note that all 3 variables are superglobals and are uppercase.



Related:




  • Notice: Undefined variable


  • Notice: Undefined Index






share|improve this answer



















  • 6




    @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.
    – IMSoP
    Oct 24 '13 at 20:00






  • 5




    Hiding the issues is NOT the way to deal with issues. Items #2...#4 can be used only on production servers, not in general.
    – Salman A
    Sep 13 '14 at 8:09








  • 1




    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..
    – Alph.Dev
    Oct 11 '14 at 14:14








  • 17




    Why is it recommended to use 1. $value = isset($_POST['value']) ? $_POST['value'] : ''; instead of using 4. $value = @$_POST['value'];?
    – forsvunnet
    Feb 9 '15 at 13: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.
    – Aycan Yaşıt
    Aug 6 '15 at 9:58




















up vote
115
down vote













Try these




Q1: this notice means $varname is not
defined at current scope of the
script.



Q2: Use of isset(), empty() conditions before using any suspicious variable works well.




// recommended solution for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';

// pre-7 PHP versions
$user_name = '';
if (!empty($_SESSION['user_name'])) {
$user_name = $_SESSION['user_name'];
}


Or, as a quick and dirty solution:



// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);




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







share|improve this answer























  • If using E_NOTICE from the php.ini configuration file, do error_reporting = (E_ALL & ~E_NOTICE)
    – ahmd0
    Oct 4 '14 at 5:39






  • 1




    This answer is being discussed on meta.
    – Script47
    Jun 25 at 10:43


















up vote
49
down vote













Error display @ operator



For undesired and redundant notices, one could use the dedicated @ operator to »hide« undefined variable/index messages.



$var = @($_GET["optional_param"]);



  • This is usually discouraged. Newcomers tend to way overuse it.

  • It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.

  • There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect @-hidden notices with: set_error_handler("var_dump");


    • Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.

    • Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add @ or isset only after verifying functionality.


    • Fix the cause first. Not the notices.






  • @ 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 input





  • First thing you do when encountering an undefined index/offset, is check for typos:
    $count = $_GET["whatnow?"];




    • Is this an expected key name and present on each page request?

    • Variable names and array indicies are case-sensitive in PHP.




  • Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:



    var_dump($_GET);
    var_dump($_POST);
    //print_r($_REQUEST);


    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:



    browser developer tools / network tab



    POST parameters and GET input will be be shown separately.




  • For $_GET parameters you can also peek at the QUERY_STRING in



    print_r($_SERVER);


    PHP 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.




    • Ensure each required input has an <input name=FOO>

    • The id= or title= attribute does not suffice.

    • A method=POST form ought to populate $_POST.

    • Whereas a method=GET (or leaving it out) would yield $_GET variables.

    • It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.

    • With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_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 the RewriteLog to figure out absent parameters.



$_FILES




  • The same sanity checks apply to file uploads and $_FILES["formname"].

  • Moreover check for enctype=multipart/form-data

  • As well as method=POST in your <form> declaration.

  • See also: PHP Undefined index error $_FILES?


$_COOKIE




  • The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.

  • Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.






share|improve this answer



















  • 2




    If you are curious what is the performance impact, this article summarises it well, derickrethans.nl/….
    – Gajus
    Feb 11 '14 at 12:24










  • @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").
    – mario
    Feb 11 '14 at 12:37










  • 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).
    – Gajus
    Feb 11 '14 at 16:30












  • I tested with PHP 5.4 and the performance still bad.
    – Brynner Ferreira
    Oct 3 '14 at 17:43


















up vote
37
down vote













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.






share|improve this answer






























    up vote
    37
    down vote













    Generally because of "bad programming", and a possibility for mistakes now or later.




    1. If it's a mistake, make a proper assignment to the variable first: $varname=0;

    2. If it really is only defined sometimes, test for it: if (isset($varname)), before using it

    3. If it's because you spelled it wrong, just correct that

    4. Maybe even turn of the warnings in you PHP-settings






    share|improve this answer



















    • 4




      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".
      – user395760
      Nov 23 '10 at 21:37








    • 4




      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.
      – Valentin Flachsel
      Nov 23 '10 at 21:38






    • 1




      @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
      – Pekka 웃
      Nov 23 '10 at 21:40










    • 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.
      – Erik
      Nov 23 '10 at 22:26


















    up vote
    32
    down vote













    I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.



    My solution was this function:



    function ifexists($varname)
    {
    return(isset($$varname)?$varname:null);
    }


    So if I want to reference to $name and echo if exists, I simply write:



    <?=ifexists('name')?>


    For array elements:



    function ifexistsidx($var,$index)
    {
    return(isset($var[$index])?$var[$index]:null);
    }


    In page if I want to refer to $_REQUEST['name']:



    <?=ifexistsidx($_REQUEST,'name')?>





    share|improve this answer



















    • 2




      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.)
      – skierpage
      Jun 19 '12 at 22:14










    • now you will get "hello from"... what's the point? just check the value if( !empty($user) and !empty($location) ) echo "hello $user ..."
      – gcb
      Jul 9 '13 at 5:31


















    up vote
    25
    down vote













    The best way for getting input string is:



    $value = filter_input(INPUT_POST, 'value');


    This one-liner is almost equivalent to:



    if (!isset($_POST['value'])) {
    $value = null;
    } elseif (is_array($_POST['value'])) {
    $value = false;
    } else {
    $value = $_POST['value'];
    }


    If you absolutely want string value, just like:



    $value = (string)filter_input(INPUT_POST, 'value');





    share|improve this answer






























      up vote
      24
      down vote













      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:



      $a=10;
      if($a==5) { $user_location='Paris';} else { }
      echo $user_location;


      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:



      $a=10;
      if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
      echo $user_location;





      share|improve this answer






























        up vote
        24
        down vote



        +25










        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 to display_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




        • .htconf (webserver configuration, including vhosts and sub-configurations)*

        • .htaccess

        • in php code itself


        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




        • Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.

        • Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed

        • Check error_reporting and display_errors php directives in .htaccess have not changed

        • If you have directive in .htaccess, check if they are still permitted in the .htconf file

        • Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.






        share|improve this answer






























          up vote
          17
          down vote













          the quick fix is to assign your variable to null at the top of your code



          $user_location = null;





          share|improve this answer






























            up vote
            15
            down vote













            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:



            // Echo whatever the hell this is
            <?=$_POST['something']?>


            ...Think again! A better solution is:



            // If this is set, echo a filtered version
            <?=isset($_POST['something']) ? html($_POST['something']) : ''?>


            (I use a custom html() function to escape characters, your mileage may vary)






            share|improve this answer






























              up vote
              13
              down vote













              I use all time own useful function exst() which automatically declare variables.



              Your code will be -



              $greeting = "Hello, ".exst($user_name, 'Visitor')." from ".exst($user_location);


              /**
              * Function exst() - Checks if the variable has been set
              * (copy/paste it in any place of your code)
              *
              * If the variable is set and not empty returns the variable (no transformation)
              * If the variable is not set or empty, returns the $default value
              *
              * @param mixed $var
              * @param mixed $default
              *
              * @return mixed
              */

              function exst( & $var, $default = "")
              {
              $t = "";
              if ( !isset($var) || !$var ) {
              if (isset($default) && $default != "") $t = $default;
              }
              else {
              $t = $var;
              }
              if (is_string($t)) $t = trim($t);
              return $t;
              }





              share|improve this answer






























                up vote
                13
                down vote













                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.




                share|improve this answer






























                  up vote
                  12
                  down vote













                  In PHP 7.0 it's now possible to use Null coalescing operator:



                  echo "My index value is: " . ($my_array["my_index"] ?? '');


                  Equals to:



                  echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');


                  PHP manual PHP 7.0






                  share|improve this answer



















                  • 1




                    Wow, this answer needs to be voted up more now that this is available in PHP 7. Wonderful solution!!!
                    – OCDev
                    Sep 24 '17 at 13:17










                  • This also works fine in if statements. if (is_array($my_array['idontexist'] ?? '')) { dosomething(); }
                    – a coder
                    Feb 23 at 20:04












                  • Your code is actually a nice overlooked bug: ?? - only checks for isset(), if you pass is_array() - which is a boolean, unexpected behavior will follow.
                    – Lachezar Lechev
                    Feb 26 at 1:20




















                  up vote
                  7
                  down vote













                  why not keep things simple?



                  <?php
                  error_reporting(E_ALL); // making sure all notices are on

                  function idxVal(&$var, $default = null) {
                  return empty($var) ? $var = $default : $var;
                  }

                  echo idxVal($arr['test']); // returns null without any notice
                  echo idxVal($arr['hey ho'], 'yo'); // returns yo and assigns it to array index, nice

                  ?>





                  share|improve this answer






























                    up vote
                    7
                    down vote













                    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.



                    ; Common Values:
                    ; E_ALL (Show all errors, warnings and notices including coding standards.)
                    ; E_ALL & ~E_NOTICE (Show all errors, except for notices)
                    ; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
                    ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
                    ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
                    ; Development Value: E_ALL
                    ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
                    ; http://php.net/error-reporting
                    error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT


                    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:




                    1. You installed PHP and the new default settings are somewhat poorly documented, but do not exclude E_NOTICE.


                    2. 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, keeping E_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?




                    1. 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 in error_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.


                    2. 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 use php_value inside of <Directory>.


                    3. 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 and log_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.



                    function foo()
                    {
                    $my_variable_name = '';

                    //....

                    if ($my_variable_name) {
                    // perform some logic
                    }
                    }


                    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.



                    // verbose way - generally better
                    if (isset($my_array['my_index'])) {
                    echo "My index value is: " . $my_array['my_index'];
                    }

                    // non-verbose ternary example - I use this sometimes for small rules.
                    $my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
                    echo "My index value is: " . $my_index_val;


                    Another option is to declare an empty array at the top of your function. This is not always possible.



                    $my_array = array(
                    'my_index' => ''
                    );

                    //...

                    $my_array['my_index'] = 'new string';


                    (additional tip)




                    • When I was encountering these and other issues, I used NetBeans IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).






                    share|improve this answer






























                      up vote
                      5
                      down vote













                      undefined index means in an array you requested for unavailable array index for example



                      <?php 

                      $newArray = {1,2,3,4,5};
                      print_r($newArray[5]);

                      ?>


                      undefined variable means you have used completely not existing variable or which is not defined or initialized by that name for example



                      <?php print_r($myvar); ?>


                      undefined offset means in array you have asked for non existing key. And the
                      solution for this is to check before use



                      php> echo array_key_exists(1, $myarray);





                      share|improve this answer






























                        up vote
                        3
                        down vote













                        Regarding this part of the question:




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




                        No definite answers but here are a some possible explanations of why settings can 'suddenly' change:




                        1. You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.


                        2. You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set() or error_reporting() (search for these in the code)


                        3. You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.


                        4. 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.







                        share|improve this answer






























                          up vote
                          2
                          down vote













                          If working with classes you need to make sure you reference member variables using $this:



                          class Person
                          {
                          protected $firstName;
                          protected $lastName;

                          public function setFullName($first, $last)
                          {
                          // Correct
                          $this->firstName = $first;

                          // Incorrect
                          $lastName = $last;

                          // Incorrect
                          $this->$lastName = $last;
                          }
                          }





                          share|improve this answer






























                            up vote
                            2
                            down vote













                            Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.



                            I.e.:



                            $query = "SELECT col1 FROM table WHERE col_x = ?";


                            Then trying to access more columns/rows inside a loop.



                            I.e.:



                            print_r($row['col1']);
                            print_r($row['col2']); // undefined index thrown


                            or in a while loop:



                            while( $row = fetching_function($query) ) {

                            echo $row['col1'];
                            echo "<br>";
                            echo $row['col2']; // undefined index thrown
                            echo "<br>";
                            echo $row['col3']; // undefined index thrown

                            }


                            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







                            share|improve this answer























                            • I have to wonder why this was downvoted also.
                              – Funk Forty Niner
                              Oct 25 at 0:26


















                            up vote
                            1
                            down vote













                            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):



                            $newVariable = isset($thePotentialData) ? $thePotentialData : null;


                            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:



                            $newVariable = $thePotentialData ?? null;


                            Both will stop the Notices from the OP question, and both are the exact equivalent of:



                            if (isset($thePotentialData)) {
                            $newVariable = $thePotentialData;
                            } else {
                            $newVariable = null;
                            }


                             

                            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:



                            echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';


                            Function:



                            $foreName = getForeName(isset($userId) ? $userId : null);

                            function getForeName($userId)
                            {
                            if ($userId === null) {
                            // Etc
                            }
                            }


                            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.






                            share|improve this answer






























                              up vote
                              0
                              down vote













                              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.






                              share|improve this answer






























                                up vote
                                0
                                down vote













                                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



                                <!-- The data encoding type, enctype, MUST be specified as below -->
                                <form enctype="multipart/form-data" action="__URL__" method="POST">
                                <!-- MAX_FILE_SIZE must precede the file input field -->
                                <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
                                <!-- Name of input element determines name in $_FILES array -->
                                Send this file: <input name="userfile" type="file" />
                                <input type="submit" value="Send File" />
                                </form>


                                PHP



                                <?php
                                // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
                                // of $_FILES.

                                $uploaddir = '/var/www/uploads/';
                                $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

                                echo '<pre>';
                                if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                                echo "File is valid, and was successfully uploaded.n";
                                } else {
                                echo "Possible file upload attack!n";
                                }

                                echo 'Here is some more debugging info:';
                                print_r($_FILES);

                                print "</pre>";

                                ?>


                                Reference:




                                • http://php.net/manual/en/features.file-upload.post-method.php






                                share|improve this answer






























                                  up vote
                                  0
                                  down vote













                                  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>



                                  <form action="example.php" method="post">
                                  <p>
                                  <input type="text" name="name" />
                                  <input type="submit" value="Submit" />
                                  </p>
                                  </form>

                                  <select name="choice">
                                  <option value="choice1">choice 1</option>
                                  <option value="choice2">choice 2</option>
                                  <option value="choice3">choice 3</option>
                                  <option value="choice4">choice 4</option>
                                  </select>


                                  Example: Element now contained within the <form>



                                  <form action="example.php" method="post">
                                  <select name="choice">
                                  <option value="choice1">choice 1</option>
                                  <option value="choice2">choice 2</option>
                                  <option value="choice3">choice 3</option>
                                  <option value="choice4">choice 4</option>
                                  </select>
                                  <p>
                                  <input type="text" name="name" />
                                  <input type="submit" value="Submit" />
                                  </p>
                                  </form>





                                  share|improve this answer






























                                    up vote
                                    0
                                    down vote













                                    I asked a question about this and I was referred to this post with the message:




                                    This question already has an answer here:



                                    “Notice: Undefined variable”, “Notice: Undefined index”, and “Notice:
                                    Undefined offset” using PHP




                                    I am sharing my question and solution here:



                                    This is the error:



                                    enter image description here



                                    Line 154 is the problem. This is what I have in line 154:



                                    153    foreach($cities as $key => $city){
                                    154 if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){


                                    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():



                                    foreach($cities as $key => $city){
                                    if(array_key_exists($key, $citiesCounterArray)){
                                    if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){





                                    share|improve this answer






























                                      up vote
                                      0
                                      down vote













                                      Different type of errors



                                      1)Notice: Undefined variable




                                      You will get this error if you have not define the variable and you
                                      are trying to access or use that variable.




                                      Example:



                                          <?php
                                      echo $a;
                                      ?>

                                      Notice: Undefined variable: a


                                      2)Notice: Undefined index & Undefined offset




                                      It means you're referring to an array key that doesn't exist. "Offset"



                                      refers to the integer key of a numeric array, and "index" refers to
                                      the



                                      string key of an associative array.




                                      <?php 
                                      $testArr=array("Test1", "Test2");

                                      print $testArr[2]; //undefined offset

                                      $myArr=array("val1"=>"1", "val2"=>"2");

                                      print $myArr['val3']; //undefined index
                                      ?>





                                      share|improve this answer






























                                        up vote
                                        -1
                                        down vote













                                        Those notices are because you don't have the used variable defined and my_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:



                                        $my_variable_name = "Variable name"; // defining variable
                                        echo "My variable value is: " . $my_variable_name;

                                        if(isset($my_array["my_index"])){
                                        echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
                                        }


                                        Another way to get this out:



                                        ini_set("error_reporting", false)





                                        share|improve this answer






























                                          up vote
                                          -1
                                          down vote













                                          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!.



                                          //If you only want to check variable has value and value has true and false value.
                                          //But variable must be defined first.

                                          if($my_variable_name){

                                          }

                                          //If you want to check variable is define or undefine
                                          //Isset() does not check that variable has true or false value
                                          //But it check null value of variable
                                          if(isset($my_variable_name)){

                                          }


                                          Simple Explanation



                                          //It will work with :- true,false,NULL
                                          $defineVarialbe = false;
                                          if($defineVarialbe){
                                          echo "true";
                                          }else{
                                          echo "false";
                                          }

                                          //It will check variable is define or not and variable has null value.
                                          if(isset($unDefineVarialbe)){
                                          echo "true";
                                          }else{
                                          echo "false";
                                          }





                                          share|improve this answer






















                                            protected by Madara Uchiha Dec 9 '12 at 12:00



                                            Thank you for your interest in this question.
                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                            Would you like to answer one of these unanswered questions instead?














                                            28 Answers
                                            28






                                            active

                                            oldest

                                            votes








                                            28 Answers
                                            28






                                            active

                                            oldest

                                            votes









                                            active

                                            oldest

                                            votes






                                            active

                                            oldest

                                            votes








                                            up vote
                                            918
                                            down vote



                                            accepted










                                            Notice: Undefined variable



                                            From the vast wisdom of 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. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.




                                            From PHP documentation:




                                            No warning is generated if the variable does not exist. That means
                                            empty() is essentially the concise equivalent to !isset($var) || $var
                                            == false
                                            .




                                            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:






                                            $o = ;
                                            @$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
                                            array_walk($var, function($v) {
                                            echo (!isset($v) || $v == false) ? 'true ' : 'false';
                                            echo ' ' . (empty($v) ? 'true' : 'false');
                                            echo "n";
                                            });


                                            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:





                                            1. 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:



                                              //Initializing variable
                                              $value = ""; //Initialization value; Examples
                                              //"" When you want to append stuff later
                                              //0 When you want to add numbers later
                                              //isset()
                                              $value = isset($_POST['value']) ? $_POST['value'] : '';
                                              //empty()
                                              $value = !empty($_POST['value']) ? $_POST['value'] : '';


                                              This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:



                                              // Null coalesce operator - No need to explicitly initialize the variable.
                                              $value = $_POST['value'] ?? '';



                                            2. Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):



                                              set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)



                                            3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:



                                              error_reporting( error_reporting() & ~E_NOTICE )


                                            4. 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:





                                            1. Check if the index exists before you access it. For this you can use isset() or array_key_exists():



                                              //isset()
                                              $value = isset($array['my_index']) ? $array['my_index'] : '';
                                              //array_key_exists()
                                              $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';



                                            2. The language construct list() may generate this when it attempts to access an array index that does not exist:



                                              list($a, $b) = array(0 => 'a');
                                              //or
                                              list($one, $two) = explode(',', 'test string');



                                            Two variables are used to access two array elements, however there is only one array element, index 0, so this will generate:




                                            Notice: Undefined offset: 1





                                            $_POST / $_GET / $_SESSION variable



                                            The 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 with session_start() and that the index also exists.



                                            Also note that all 3 variables are superglobals and are uppercase.



                                            Related:




                                            • Notice: Undefined variable


                                            • Notice: Undefined Index






                                            share|improve this answer



















                                            • 6




                                              @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.
                                              – IMSoP
                                              Oct 24 '13 at 20:00






                                            • 5




                                              Hiding the issues is NOT the way to deal with issues. Items #2...#4 can be used only on production servers, not in general.
                                              – Salman A
                                              Sep 13 '14 at 8:09








                                            • 1




                                              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..
                                              – Alph.Dev
                                              Oct 11 '14 at 14:14








                                            • 17




                                              Why is it recommended to use 1. $value = isset($_POST['value']) ? $_POST['value'] : ''; instead of using 4. $value = @$_POST['value'];?
                                              – forsvunnet
                                              Feb 9 '15 at 13: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.
                                              – Aycan Yaşıt
                                              Aug 6 '15 at 9:58

















                                            up vote
                                            918
                                            down vote



                                            accepted










                                            Notice: Undefined variable



                                            From the vast wisdom of 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. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.




                                            From PHP documentation:




                                            No warning is generated if the variable does not exist. That means
                                            empty() is essentially the concise equivalent to !isset($var) || $var
                                            == false
                                            .




                                            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:






                                            $o = ;
                                            @$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
                                            array_walk($var, function($v) {
                                            echo (!isset($v) || $v == false) ? 'true ' : 'false';
                                            echo ' ' . (empty($v) ? 'true' : 'false');
                                            echo "n";
                                            });


                                            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:





                                            1. 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:



                                              //Initializing variable
                                              $value = ""; //Initialization value; Examples
                                              //"" When you want to append stuff later
                                              //0 When you want to add numbers later
                                              //isset()
                                              $value = isset($_POST['value']) ? $_POST['value'] : '';
                                              //empty()
                                              $value = !empty($_POST['value']) ? $_POST['value'] : '';


                                              This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:



                                              // Null coalesce operator - No need to explicitly initialize the variable.
                                              $value = $_POST['value'] ?? '';



                                            2. Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):



                                              set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)



                                            3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:



                                              error_reporting( error_reporting() & ~E_NOTICE )


                                            4. 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:





                                            1. Check if the index exists before you access it. For this you can use isset() or array_key_exists():



                                              //isset()
                                              $value = isset($array['my_index']) ? $array['my_index'] : '';
                                              //array_key_exists()
                                              $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';



                                            2. The language construct list() may generate this when it attempts to access an array index that does not exist:



                                              list($a, $b) = array(0 => 'a');
                                              //or
                                              list($one, $two) = explode(',', 'test string');



                                            Two variables are used to access two array elements, however there is only one array element, index 0, so this will generate:




                                            Notice: Undefined offset: 1





                                            $_POST / $_GET / $_SESSION variable



                                            The 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 with session_start() and that the index also exists.



                                            Also note that all 3 variables are superglobals and are uppercase.



                                            Related:




                                            • Notice: Undefined variable


                                            • Notice: Undefined Index






                                            share|improve this answer



















                                            • 6




                                              @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.
                                              – IMSoP
                                              Oct 24 '13 at 20:00






                                            • 5




                                              Hiding the issues is NOT the way to deal with issues. Items #2...#4 can be used only on production servers, not in general.
                                              – Salman A
                                              Sep 13 '14 at 8:09








                                            • 1




                                              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..
                                              – Alph.Dev
                                              Oct 11 '14 at 14:14








                                            • 17




                                              Why is it recommended to use 1. $value = isset($_POST['value']) ? $_POST['value'] : ''; instead of using 4. $value = @$_POST['value'];?
                                              – forsvunnet
                                              Feb 9 '15 at 13: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.
                                              – Aycan Yaşıt
                                              Aug 6 '15 at 9:58















                                            up vote
                                            918
                                            down vote



                                            accepted







                                            up vote
                                            918
                                            down vote



                                            accepted






                                            Notice: Undefined variable



                                            From the vast wisdom of 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. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.




                                            From PHP documentation:




                                            No warning is generated if the variable does not exist. That means
                                            empty() is essentially the concise equivalent to !isset($var) || $var
                                            == false
                                            .




                                            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:






                                            $o = ;
                                            @$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
                                            array_walk($var, function($v) {
                                            echo (!isset($v) || $v == false) ? 'true ' : 'false';
                                            echo ' ' . (empty($v) ? 'true' : 'false');
                                            echo "n";
                                            });


                                            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:





                                            1. 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:



                                              //Initializing variable
                                              $value = ""; //Initialization value; Examples
                                              //"" When you want to append stuff later
                                              //0 When you want to add numbers later
                                              //isset()
                                              $value = isset($_POST['value']) ? $_POST['value'] : '';
                                              //empty()
                                              $value = !empty($_POST['value']) ? $_POST['value'] : '';


                                              This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:



                                              // Null coalesce operator - No need to explicitly initialize the variable.
                                              $value = $_POST['value'] ?? '';



                                            2. Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):



                                              set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)



                                            3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:



                                              error_reporting( error_reporting() & ~E_NOTICE )


                                            4. 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:





                                            1. Check if the index exists before you access it. For this you can use isset() or array_key_exists():



                                              //isset()
                                              $value = isset($array['my_index']) ? $array['my_index'] : '';
                                              //array_key_exists()
                                              $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';



                                            2. The language construct list() may generate this when it attempts to access an array index that does not exist:



                                              list($a, $b) = array(0 => 'a');
                                              //or
                                              list($one, $two) = explode(',', 'test string');



                                            Two variables are used to access two array elements, however there is only one array element, index 0, so this will generate:




                                            Notice: Undefined offset: 1





                                            $_POST / $_GET / $_SESSION variable



                                            The 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 with session_start() and that the index also exists.



                                            Also note that all 3 variables are superglobals and are uppercase.



                                            Related:




                                            • Notice: Undefined variable


                                            • Notice: Undefined Index






                                            share|improve this answer














                                            Notice: Undefined variable



                                            From the vast wisdom of 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. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.




                                            From PHP documentation:




                                            No warning is generated if the variable does not exist. That means
                                            empty() is essentially the concise equivalent to !isset($var) || $var
                                            == false
                                            .




                                            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:






                                            $o = ;
                                            @$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
                                            array_walk($var, function($v) {
                                            echo (!isset($v) || $v == false) ? 'true ' : 'false';
                                            echo ' ' . (empty($v) ? 'true' : 'false');
                                            echo "n";
                                            });


                                            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:





                                            1. 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:



                                              //Initializing variable
                                              $value = ""; //Initialization value; Examples
                                              //"" When you want to append stuff later
                                              //0 When you want to add numbers later
                                              //isset()
                                              $value = isset($_POST['value']) ? $_POST['value'] : '';
                                              //empty()
                                              $value = !empty($_POST['value']) ? $_POST['value'] : '';


                                              This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:



                                              // Null coalesce operator - No need to explicitly initialize the variable.
                                              $value = $_POST['value'] ?? '';



                                            2. Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):



                                              set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)



                                            3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:



                                              error_reporting( error_reporting() & ~E_NOTICE )


                                            4. 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:





                                            1. Check if the index exists before you access it. For this you can use isset() or array_key_exists():



                                              //isset()
                                              $value = isset($array['my_index']) ? $array['my_index'] : '';
                                              //array_key_exists()
                                              $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';



                                            2. The language construct list() may generate this when it attempts to access an array index that does not exist:



                                              list($a, $b) = array(0 => 'a');
                                              //or
                                              list($one, $two) = explode(',', 'test string');



                                            Two variables are used to access two array elements, however there is only one array element, index 0, so this will generate:




                                            Notice: Undefined offset: 1





                                            $_POST / $_GET / $_SESSION variable



                                            The 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 with session_start() and that the index also exists.



                                            Also note that all 3 variables are superglobals and are uppercase.



                                            Related:




                                            • Notice: Undefined variable


                                            • Notice: Undefined Index







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited May 25 at 18:40


























                                            community wiki





                                            23 revs, 11 users 27%
                                            Rizier123









                                            • 6




                                              @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.
                                              – IMSoP
                                              Oct 24 '13 at 20:00






                                            • 5




                                              Hiding the issues is NOT the way to deal with issues. Items #2...#4 can be used only on production servers, not in general.
                                              – Salman A
                                              Sep 13 '14 at 8:09








                                            • 1




                                              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..
                                              – Alph.Dev
                                              Oct 11 '14 at 14:14








                                            • 17




                                              Why is it recommended to use 1. $value = isset($_POST['value']) ? $_POST['value'] : ''; instead of using 4. $value = @$_POST['value'];?
                                              – forsvunnet
                                              Feb 9 '15 at 13: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.
                                              – Aycan Yaşıt
                                              Aug 6 '15 at 9:58
















                                            • 6




                                              @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.
                                              – IMSoP
                                              Oct 24 '13 at 20:00






                                            • 5




                                              Hiding the issues is NOT the way to deal with issues. Items #2...#4 can be used only on production servers, not in general.
                                              – Salman A
                                              Sep 13 '14 at 8:09








                                            • 1




                                              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..
                                              – Alph.Dev
                                              Oct 11 '14 at 14:14








                                            • 17




                                              Why is it recommended to use 1. $value = isset($_POST['value']) ? $_POST['value'] : ''; instead of using 4. $value = @$_POST['value'];?
                                              – forsvunnet
                                              Feb 9 '15 at 13: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.
                                              – Aycan Yaşıt
                                              Aug 6 '15 at 9:58










                                            6




                                            6




                                            @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.
                                            – IMSoP
                                            Oct 24 '13 at 20:00




                                            @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.
                                            – IMSoP
                                            Oct 24 '13 at 20:00




                                            5




                                            5




                                            Hiding the issues is NOT the way to deal with issues. Items #2...#4 can be used only on production servers, not in general.
                                            – Salman A
                                            Sep 13 '14 at 8:09






                                            Hiding the issues is NOT the way to deal with issues. Items #2...#4 can be used only on production servers, not in general.
                                            – Salman A
                                            Sep 13 '14 at 8:09






                                            1




                                            1




                                            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..
                                            – Alph.Dev
                                            Oct 11 '14 at 14:14






                                            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..
                                            – Alph.Dev
                                            Oct 11 '14 at 14:14






                                            17




                                            17




                                            Why is it recommended to use 1. $value = isset($_POST['value']) ? $_POST['value'] : ''; instead of using 4. $value = @$_POST['value'];?
                                            – forsvunnet
                                            Feb 9 '15 at 13:38




                                            Why is it recommended to use 1. $value = isset($_POST['value']) ? $_POST['value'] : ''; instead of using 4. $value = @$_POST['value'];?
                                            – forsvunnet
                                            Feb 9 '15 at 13: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.
                                            – Aycan Yaşıt
                                            Aug 6 '15 at 9:58






                                            @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.
                                            – Aycan Yaşıt
                                            Aug 6 '15 at 9:58














                                            up vote
                                            115
                                            down vote













                                            Try these




                                            Q1: this notice means $varname is not
                                            defined at current scope of the
                                            script.



                                            Q2: Use of isset(), empty() conditions before using any suspicious variable works well.




                                            // recommended solution for recent PHP versions
                                            $user_name = $_SESSION['user_name'] ?? '';

                                            // pre-7 PHP versions
                                            $user_name = '';
                                            if (!empty($_SESSION['user_name'])) {
                                            $user_name = $_SESSION['user_name'];
                                            }


                                            Or, as a quick and dirty solution:



                                            // not the best solution, but works
                                            // in your php setting use, it helps hiding site wide notices
                                            error_reporting(E_ALL ^ E_NOTICE);




                                            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







                                            share|improve this answer























                                            • If using E_NOTICE from the php.ini configuration file, do error_reporting = (E_ALL & ~E_NOTICE)
                                              – ahmd0
                                              Oct 4 '14 at 5:39






                                            • 1




                                              This answer is being discussed on meta.
                                              – Script47
                                              Jun 25 at 10:43















                                            up vote
                                            115
                                            down vote













                                            Try these




                                            Q1: this notice means $varname is not
                                            defined at current scope of the
                                            script.



                                            Q2: Use of isset(), empty() conditions before using any suspicious variable works well.




                                            // recommended solution for recent PHP versions
                                            $user_name = $_SESSION['user_name'] ?? '';

                                            // pre-7 PHP versions
                                            $user_name = '';
                                            if (!empty($_SESSION['user_name'])) {
                                            $user_name = $_SESSION['user_name'];
                                            }


                                            Or, as a quick and dirty solution:



                                            // not the best solution, but works
                                            // in your php setting use, it helps hiding site wide notices
                                            error_reporting(E_ALL ^ E_NOTICE);




                                            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







                                            share|improve this answer























                                            • If using E_NOTICE from the php.ini configuration file, do error_reporting = (E_ALL & ~E_NOTICE)
                                              – ahmd0
                                              Oct 4 '14 at 5:39






                                            • 1




                                              This answer is being discussed on meta.
                                              – Script47
                                              Jun 25 at 10:43













                                            up vote
                                            115
                                            down vote










                                            up vote
                                            115
                                            down vote









                                            Try these




                                            Q1: this notice means $varname is not
                                            defined at current scope of the
                                            script.



                                            Q2: Use of isset(), empty() conditions before using any suspicious variable works well.




                                            // recommended solution for recent PHP versions
                                            $user_name = $_SESSION['user_name'] ?? '';

                                            // pre-7 PHP versions
                                            $user_name = '';
                                            if (!empty($_SESSION['user_name'])) {
                                            $user_name = $_SESSION['user_name'];
                                            }


                                            Or, as a quick and dirty solution:



                                            // not the best solution, but works
                                            // in your php setting use, it helps hiding site wide notices
                                            error_reporting(E_ALL ^ E_NOTICE);




                                            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







                                            share|improve this answer














                                            Try these




                                            Q1: this notice means $varname is not
                                            defined at current scope of the
                                            script.



                                            Q2: Use of isset(), empty() conditions before using any suspicious variable works well.




                                            // recommended solution for recent PHP versions
                                            $user_name = $_SESSION['user_name'] ?? '';

                                            // pre-7 PHP versions
                                            $user_name = '';
                                            if (!empty($_SESSION['user_name'])) {
                                            $user_name = $_SESSION['user_name'];
                                            }


                                            Or, as a quick and dirty solution:



                                            // not the best solution, but works
                                            // in your php setting use, it helps hiding site wide notices
                                            error_reporting(E_ALL ^ E_NOTICE);




                                            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








                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Jun 26 at 14:58


























                                            community wiki





                                            9 revs, 5 users 62%
                                            Ish













                                            • If using E_NOTICE from the php.ini configuration file, do error_reporting = (E_ALL & ~E_NOTICE)
                                              – ahmd0
                                              Oct 4 '14 at 5:39






                                            • 1




                                              This answer is being discussed on meta.
                                              – Script47
                                              Jun 25 at 10:43


















                                            • If using E_NOTICE from the php.ini configuration file, do error_reporting = (E_ALL & ~E_NOTICE)
                                              – ahmd0
                                              Oct 4 '14 at 5:39






                                            • 1




                                              This answer is being discussed on meta.
                                              – Script47
                                              Jun 25 at 10:43
















                                            If using E_NOTICE from the php.ini configuration file, do error_reporting = (E_ALL & ~E_NOTICE)
                                            – ahmd0
                                            Oct 4 '14 at 5:39




                                            If using E_NOTICE from the php.ini configuration file, do error_reporting = (E_ALL & ~E_NOTICE)
                                            – ahmd0
                                            Oct 4 '14 at 5:39




                                            1




                                            1




                                            This answer is being discussed on meta.
                                            – Script47
                                            Jun 25 at 10:43




                                            This answer is being discussed on meta.
                                            – Script47
                                            Jun 25 at 10:43










                                            up vote
                                            49
                                            down vote













                                            Error display @ operator



                                            For undesired and redundant notices, one could use the dedicated @ operator to »hide« undefined variable/index messages.



                                            $var = @($_GET["optional_param"]);



                                            • This is usually discouraged. Newcomers tend to way overuse it.

                                            • It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.

                                            • There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect @-hidden notices with: set_error_handler("var_dump");


                                              • Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.

                                              • Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add @ or isset only after verifying functionality.


                                              • Fix the cause first. Not the notices.






                                            • @ 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 input





                                            • First thing you do when encountering an undefined index/offset, is check for typos:
                                              $count = $_GET["whatnow?"];




                                              • Is this an expected key name and present on each page request?

                                              • Variable names and array indicies are case-sensitive in PHP.




                                            • Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:



                                              var_dump($_GET);
                                              var_dump($_POST);
                                              //print_r($_REQUEST);


                                              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:



                                              browser developer tools / network tab



                                              POST parameters and GET input will be be shown separately.




                                            • For $_GET parameters you can also peek at the QUERY_STRING in



                                              print_r($_SERVER);


                                              PHP 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.




                                              • Ensure each required input has an <input name=FOO>

                                              • The id= or title= attribute does not suffice.

                                              • A method=POST form ought to populate $_POST.

                                              • Whereas a method=GET (or leaving it out) would yield $_GET variables.

                                              • It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.

                                              • With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_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 the RewriteLog to figure out absent parameters.



                                            $_FILES




                                            • The same sanity checks apply to file uploads and $_FILES["formname"].

                                            • Moreover check for enctype=multipart/form-data

                                            • As well as method=POST in your <form> declaration.

                                            • See also: PHP Undefined index error $_FILES?


                                            $_COOKIE




                                            • The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.

                                            • Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.






                                            share|improve this answer



















                                            • 2




                                              If you are curious what is the performance impact, this article summarises it well, derickrethans.nl/….
                                              – Gajus
                                              Feb 11 '14 at 12:24










                                            • @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").
                                              – mario
                                              Feb 11 '14 at 12:37










                                            • 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).
                                              – Gajus
                                              Feb 11 '14 at 16:30












                                            • I tested with PHP 5.4 and the performance still bad.
                                              – Brynner Ferreira
                                              Oct 3 '14 at 17:43















                                            up vote
                                            49
                                            down vote













                                            Error display @ operator



                                            For undesired and redundant notices, one could use the dedicated @ operator to »hide« undefined variable/index messages.



                                            $var = @($_GET["optional_param"]);



                                            • This is usually discouraged. Newcomers tend to way overuse it.

                                            • It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.

                                            • There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect @-hidden notices with: set_error_handler("var_dump");


                                              • Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.

                                              • Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add @ or isset only after verifying functionality.


                                              • Fix the cause first. Not the notices.






                                            • @ 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 input





                                            • First thing you do when encountering an undefined index/offset, is check for typos:
                                              $count = $_GET["whatnow?"];




                                              • Is this an expected key name and present on each page request?

                                              • Variable names and array indicies are case-sensitive in PHP.




                                            • Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:



                                              var_dump($_GET);
                                              var_dump($_POST);
                                              //print_r($_REQUEST);


                                              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:



                                              browser developer tools / network tab



                                              POST parameters and GET input will be be shown separately.




                                            • For $_GET parameters you can also peek at the QUERY_STRING in



                                              print_r($_SERVER);


                                              PHP 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.




                                              • Ensure each required input has an <input name=FOO>

                                              • The id= or title= attribute does not suffice.

                                              • A method=POST form ought to populate $_POST.

                                              • Whereas a method=GET (or leaving it out) would yield $_GET variables.

                                              • It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.

                                              • With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_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 the RewriteLog to figure out absent parameters.



                                            $_FILES




                                            • The same sanity checks apply to file uploads and $_FILES["formname"].

                                            • Moreover check for enctype=multipart/form-data

                                            • As well as method=POST in your <form> declaration.

                                            • See also: PHP Undefined index error $_FILES?


                                            $_COOKIE




                                            • The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.

                                            • Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.






                                            share|improve this answer



















                                            • 2




                                              If you are curious what is the performance impact, this article summarises it well, derickrethans.nl/….
                                              – Gajus
                                              Feb 11 '14 at 12:24










                                            • @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").
                                              – mario
                                              Feb 11 '14 at 12:37










                                            • 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).
                                              – Gajus
                                              Feb 11 '14 at 16:30












                                            • I tested with PHP 5.4 and the performance still bad.
                                              – Brynner Ferreira
                                              Oct 3 '14 at 17:43













                                            up vote
                                            49
                                            down vote










                                            up vote
                                            49
                                            down vote









                                            Error display @ operator



                                            For undesired and redundant notices, one could use the dedicated @ operator to »hide« undefined variable/index messages.



                                            $var = @($_GET["optional_param"]);



                                            • This is usually discouraged. Newcomers tend to way overuse it.

                                            • It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.

                                            • There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect @-hidden notices with: set_error_handler("var_dump");


                                              • Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.

                                              • Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add @ or isset only after verifying functionality.


                                              • Fix the cause first. Not the notices.






                                            • @ 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 input





                                            • First thing you do when encountering an undefined index/offset, is check for typos:
                                              $count = $_GET["whatnow?"];




                                              • Is this an expected key name and present on each page request?

                                              • Variable names and array indicies are case-sensitive in PHP.




                                            • Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:



                                              var_dump($_GET);
                                              var_dump($_POST);
                                              //print_r($_REQUEST);


                                              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:



                                              browser developer tools / network tab



                                              POST parameters and GET input will be be shown separately.




                                            • For $_GET parameters you can also peek at the QUERY_STRING in



                                              print_r($_SERVER);


                                              PHP 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.




                                              • Ensure each required input has an <input name=FOO>

                                              • The id= or title= attribute does not suffice.

                                              • A method=POST form ought to populate $_POST.

                                              • Whereas a method=GET (or leaving it out) would yield $_GET variables.

                                              • It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.

                                              • With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_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 the RewriteLog to figure out absent parameters.



                                            $_FILES




                                            • The same sanity checks apply to file uploads and $_FILES["formname"].

                                            • Moreover check for enctype=multipart/form-data

                                            • As well as method=POST in your <form> declaration.

                                            • See also: PHP Undefined index error $_FILES?


                                            $_COOKIE




                                            • The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.

                                            • Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.






                                            share|improve this answer














                                            Error display @ operator



                                            For undesired and redundant notices, one could use the dedicated @ operator to »hide« undefined variable/index messages.



                                            $var = @($_GET["optional_param"]);



                                            • This is usually discouraged. Newcomers tend to way overuse it.

                                            • It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.

                                            • There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect @-hidden notices with: set_error_handler("var_dump");


                                              • Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.

                                              • Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add @ or isset only after verifying functionality.


                                              • Fix the cause first. Not the notices.






                                            • @ 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 input





                                            • First thing you do when encountering an undefined index/offset, is check for typos:
                                              $count = $_GET["whatnow?"];




                                              • Is this an expected key name and present on each page request?

                                              • Variable names and array indicies are case-sensitive in PHP.




                                            • Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:



                                              var_dump($_GET);
                                              var_dump($_POST);
                                              //print_r($_REQUEST);


                                              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:



                                              browser developer tools / network tab



                                              POST parameters and GET input will be be shown separately.




                                            • For $_GET parameters you can also peek at the QUERY_STRING in



                                              print_r($_SERVER);


                                              PHP 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.




                                              • Ensure each required input has an <input name=FOO>

                                              • The id= or title= attribute does not suffice.

                                              • A method=POST form ought to populate $_POST.

                                              • Whereas a method=GET (or leaving it out) would yield $_GET variables.

                                              • It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.

                                              • With modern PHP configurations (≥ 5.6) it has become feasible (not fashionable) to use $_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 the RewriteLog to figure out absent parameters.



                                            $_FILES




                                            • The same sanity checks apply to file uploads and $_FILES["formname"].

                                            • Moreover check for enctype=multipart/form-data

                                            • As well as method=POST in your <form> declaration.

                                            • See also: PHP Undefined index error $_FILES?


                                            $_COOKIE




                                            • The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.

                                            • Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Aug 22 at 21:16


























                                            community wiki





                                            3 revs
                                            mario









                                            • 2




                                              If you are curious what is the performance impact, this article summarises it well, derickrethans.nl/….
                                              – Gajus
                                              Feb 11 '14 at 12:24










                                            • @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").
                                              – mario
                                              Feb 11 '14 at 12:37










                                            • 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).
                                              – Gajus
                                              Feb 11 '14 at 16:30












                                            • I tested with PHP 5.4 and the performance still bad.
                                              – Brynner Ferreira
                                              Oct 3 '14 at 17:43














                                            • 2




                                              If you are curious what is the performance impact, this article summarises it well, derickrethans.nl/….
                                              – Gajus
                                              Feb 11 '14 at 12:24










                                            • @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").
                                              – mario
                                              Feb 11 '14 at 12:37










                                            • 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).
                                              – Gajus
                                              Feb 11 '14 at 16:30












                                            • I tested with PHP 5.4 and the performance still bad.
                                              – Brynner Ferreira
                                              Oct 3 '14 at 17:43








                                            2




                                            2




                                            If you are curious what is the performance impact, this article summarises it well, derickrethans.nl/….
                                            – Gajus
                                            Feb 11 '14 at 12:24




                                            If you are curious what is the performance impact, this article summarises it well, derickrethans.nl/….
                                            – Gajus
                                            Feb 11 '14 at 12:24












                                            @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").
                                            – mario
                                            Feb 11 '14 at 12:37




                                            @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").
                                            – mario
                                            Feb 11 '14 at 12:37












                                            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).
                                            – Gajus
                                            Feb 11 '14 at 16:30






                                            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).
                                            – Gajus
                                            Feb 11 '14 at 16:30














                                            I tested with PHP 5.4 and the performance still bad.
                                            – Brynner Ferreira
                                            Oct 3 '14 at 17:43




                                            I tested with PHP 5.4 and the performance still bad.
                                            – Brynner Ferreira
                                            Oct 3 '14 at 17:43










                                            up vote
                                            37
                                            down vote













                                            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.






                                            share|improve this answer



























                                              up vote
                                              37
                                              down vote













                                              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.






                                              share|improve this answer

























                                                up vote
                                                37
                                                down vote










                                                up vote
                                                37
                                                down vote









                                                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.






                                                share|improve this answer














                                                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.







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Nov 24 '10 at 2:43


























                                                community wiki





                                                2 revs
                                                DGM























                                                    up vote
                                                    37
                                                    down vote













                                                    Generally because of "bad programming", and a possibility for mistakes now or later.




                                                    1. If it's a mistake, make a proper assignment to the variable first: $varname=0;

                                                    2. If it really is only defined sometimes, test for it: if (isset($varname)), before using it

                                                    3. If it's because you spelled it wrong, just correct that

                                                    4. Maybe even turn of the warnings in you PHP-settings






                                                    share|improve this answer



















                                                    • 4




                                                      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".
                                                      – user395760
                                                      Nov 23 '10 at 21:37








                                                    • 4




                                                      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.
                                                      – Valentin Flachsel
                                                      Nov 23 '10 at 21:38






                                                    • 1




                                                      @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
                                                      – Pekka 웃
                                                      Nov 23 '10 at 21:40










                                                    • 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.
                                                      – Erik
                                                      Nov 23 '10 at 22:26















                                                    up vote
                                                    37
                                                    down vote













                                                    Generally because of "bad programming", and a possibility for mistakes now or later.




                                                    1. If it's a mistake, make a proper assignment to the variable first: $varname=0;

                                                    2. If it really is only defined sometimes, test for it: if (isset($varname)), before using it

                                                    3. If it's because you spelled it wrong, just correct that

                                                    4. Maybe even turn of the warnings in you PHP-settings






                                                    share|improve this answer



















                                                    • 4




                                                      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".
                                                      – user395760
                                                      Nov 23 '10 at 21:37








                                                    • 4




                                                      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.
                                                      – Valentin Flachsel
                                                      Nov 23 '10 at 21:38






                                                    • 1




                                                      @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
                                                      – Pekka 웃
                                                      Nov 23 '10 at 21:40










                                                    • 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.
                                                      – Erik
                                                      Nov 23 '10 at 22:26













                                                    up vote
                                                    37
                                                    down vote










                                                    up vote
                                                    37
                                                    down vote









                                                    Generally because of "bad programming", and a possibility for mistakes now or later.




                                                    1. If it's a mistake, make a proper assignment to the variable first: $varname=0;

                                                    2. If it really is only defined sometimes, test for it: if (isset($varname)), before using it

                                                    3. If it's because you spelled it wrong, just correct that

                                                    4. Maybe even turn of the warnings in you PHP-settings






                                                    share|improve this answer














                                                    Generally because of "bad programming", and a possibility for mistakes now or later.




                                                    1. If it's a mistake, make a proper assignment to the variable first: $varname=0;

                                                    2. If it really is only defined sometimes, test for it: if (isset($varname)), before using it

                                                    3. If it's because you spelled it wrong, just correct that

                                                    4. Maybe even turn of the warnings in you PHP-settings







                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Apr 11 at 8:46


























                                                    community wiki





                                                    2 revs, 2 users 83%
                                                    Erik









                                                    • 4




                                                      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".
                                                      – user395760
                                                      Nov 23 '10 at 21:37








                                                    • 4




                                                      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.
                                                      – Valentin Flachsel
                                                      Nov 23 '10 at 21:38






                                                    • 1




                                                      @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
                                                      – Pekka 웃
                                                      Nov 23 '10 at 21:40










                                                    • 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.
                                                      – Erik
                                                      Nov 23 '10 at 22:26














                                                    • 4




                                                      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".
                                                      – user395760
                                                      Nov 23 '10 at 21:37








                                                    • 4




                                                      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.
                                                      – Valentin Flachsel
                                                      Nov 23 '10 at 21:38






                                                    • 1




                                                      @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
                                                      – Pekka 웃
                                                      Nov 23 '10 at 21:40










                                                    • 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.
                                                      – Erik
                                                      Nov 23 '10 at 22:26








                                                    4




                                                    4




                                                    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".
                                                    – user395760
                                                    Nov 23 '10 at 21:37






                                                    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".
                                                    – user395760
                                                    Nov 23 '10 at 21:37






                                                    4




                                                    4




                                                    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.
                                                    – Valentin Flachsel
                                                    Nov 23 '10 at 21:38




                                                    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.
                                                    – Valentin Flachsel
                                                    Nov 23 '10 at 21:38




                                                    1




                                                    1




                                                    @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
                                                    – Pekka 웃
                                                    Nov 23 '10 at 21:40




                                                    @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
                                                    – Pekka 웃
                                                    Nov 23 '10 at 21:40












                                                    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.
                                                    – Erik
                                                    Nov 23 '10 at 22:26




                                                    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.
                                                    – Erik
                                                    Nov 23 '10 at 22:26










                                                    up vote
                                                    32
                                                    down vote













                                                    I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.



                                                    My solution was this function:



                                                    function ifexists($varname)
                                                    {
                                                    return(isset($$varname)?$varname:null);
                                                    }


                                                    So if I want to reference to $name and echo if exists, I simply write:



                                                    <?=ifexists('name')?>


                                                    For array elements:



                                                    function ifexistsidx($var,$index)
                                                    {
                                                    return(isset($var[$index])?$var[$index]:null);
                                                    }


                                                    In page if I want to refer to $_REQUEST['name']:



                                                    <?=ifexistsidx($_REQUEST,'name')?>





                                                    share|improve this answer



















                                                    • 2




                                                      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.)
                                                      – skierpage
                                                      Jun 19 '12 at 22:14










                                                    • now you will get "hello from"... what's the point? just check the value if( !empty($user) and !empty($location) ) echo "hello $user ..."
                                                      – gcb
                                                      Jul 9 '13 at 5:31















                                                    up vote
                                                    32
                                                    down vote













                                                    I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.



                                                    My solution was this function:



                                                    function ifexists($varname)
                                                    {
                                                    return(isset($$varname)?$varname:null);
                                                    }


                                                    So if I want to reference to $name and echo if exists, I simply write:



                                                    <?=ifexists('name')?>


                                                    For array elements:



                                                    function ifexistsidx($var,$index)
                                                    {
                                                    return(isset($var[$index])?$var[$index]:null);
                                                    }


                                                    In page if I want to refer to $_REQUEST['name']:



                                                    <?=ifexistsidx($_REQUEST,'name')?>





                                                    share|improve this answer



















                                                    • 2




                                                      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.)
                                                      – skierpage
                                                      Jun 19 '12 at 22:14










                                                    • now you will get "hello from"... what's the point? just check the value if( !empty($user) and !empty($location) ) echo "hello $user ..."
                                                      – gcb
                                                      Jul 9 '13 at 5:31













                                                    up vote
                                                    32
                                                    down vote










                                                    up vote
                                                    32
                                                    down vote









                                                    I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.



                                                    My solution was this function:



                                                    function ifexists($varname)
                                                    {
                                                    return(isset($$varname)?$varname:null);
                                                    }


                                                    So if I want to reference to $name and echo if exists, I simply write:



                                                    <?=ifexists('name')?>


                                                    For array elements:



                                                    function ifexistsidx($var,$index)
                                                    {
                                                    return(isset($var[$index])?$var[$index]:null);
                                                    }


                                                    In page if I want to refer to $_REQUEST['name']:



                                                    <?=ifexistsidx($_REQUEST,'name')?>





                                                    share|improve this answer














                                                    I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.



                                                    My solution was this function:



                                                    function ifexists($varname)
                                                    {
                                                    return(isset($$varname)?$varname:null);
                                                    }


                                                    So if I want to reference to $name and echo if exists, I simply write:



                                                    <?=ifexists('name')?>


                                                    For array elements:



                                                    function ifexistsidx($var,$index)
                                                    {
                                                    return(isset($var[$index])?$var[$index]:null);
                                                    }


                                                    In page if I want to refer to $_REQUEST['name']:



                                                    <?=ifexistsidx($_REQUEST,'name')?>






                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    answered Dec 30 '11 at 14:14


























                                                    community wiki





                                                    Ferenci Zoltán László









                                                    • 2




                                                      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.)
                                                      – skierpage
                                                      Jun 19 '12 at 22:14










                                                    • now you will get "hello from"... what's the point? just check the value if( !empty($user) and !empty($location) ) echo "hello $user ..."
                                                      – gcb
                                                      Jul 9 '13 at 5:31














                                                    • 2




                                                      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.)
                                                      – skierpage
                                                      Jun 19 '12 at 22:14










                                                    • now you will get "hello from"... what's the point? just check the value if( !empty($user) and !empty($location) ) echo "hello $user ..."
                                                      – gcb
                                                      Jul 9 '13 at 5:31








                                                    2




                                                    2




                                                    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.)
                                                    – skierpage
                                                    Jun 19 '12 at 22:14




                                                    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.)
                                                    – skierpage
                                                    Jun 19 '12 at 22:14












                                                    now you will get "hello from"... what's the point? just check the value if( !empty($user) and !empty($location) ) echo "hello $user ..."
                                                    – gcb
                                                    Jul 9 '13 at 5:31




                                                    now you will get "hello from"... what's the point? just check the value if( !empty($user) and !empty($location) ) echo "hello $user ..."
                                                    – gcb
                                                    Jul 9 '13 at 5:31










                                                    up vote
                                                    25
                                                    down vote













                                                    The best way for getting input string is:



                                                    $value = filter_input(INPUT_POST, 'value');


                                                    This one-liner is almost equivalent to:



                                                    if (!isset($_POST['value'])) {
                                                    $value = null;
                                                    } elseif (is_array($_POST['value'])) {
                                                    $value = false;
                                                    } else {
                                                    $value = $_POST['value'];
                                                    }


                                                    If you absolutely want string value, just like:



                                                    $value = (string)filter_input(INPUT_POST, 'value');





                                                    share|improve this answer



























                                                      up vote
                                                      25
                                                      down vote













                                                      The best way for getting input string is:



                                                      $value = filter_input(INPUT_POST, 'value');


                                                      This one-liner is almost equivalent to:



                                                      if (!isset($_POST['value'])) {
                                                      $value = null;
                                                      } elseif (is_array($_POST['value'])) {
                                                      $value = false;
                                                      } else {
                                                      $value = $_POST['value'];
                                                      }


                                                      If you absolutely want string value, just like:



                                                      $value = (string)filter_input(INPUT_POST, 'value');





                                                      share|improve this answer

























                                                        up vote
                                                        25
                                                        down vote










                                                        up vote
                                                        25
                                                        down vote









                                                        The best way for getting input string is:



                                                        $value = filter_input(INPUT_POST, 'value');


                                                        This one-liner is almost equivalent to:



                                                        if (!isset($_POST['value'])) {
                                                        $value = null;
                                                        } elseif (is_array($_POST['value'])) {
                                                        $value = false;
                                                        } else {
                                                        $value = $_POST['value'];
                                                        }


                                                        If you absolutely want string value, just like:



                                                        $value = (string)filter_input(INPUT_POST, 'value');





                                                        share|improve this answer














                                                        The best way for getting input string is:



                                                        $value = filter_input(INPUT_POST, 'value');


                                                        This one-liner is almost equivalent to:



                                                        if (!isset($_POST['value'])) {
                                                        $value = null;
                                                        } elseif (is_array($_POST['value'])) {
                                                        $value = false;
                                                        } else {
                                                        $value = $_POST['value'];
                                                        }


                                                        If you absolutely want string value, just like:



                                                        $value = (string)filter_input(INPUT_POST, 'value');






                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        answered Aug 26 '14 at 22:15


























                                                        community wiki





                                                        mpyw























                                                            up vote
                                                            24
                                                            down vote













                                                            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:



                                                            $a=10;
                                                            if($a==5) { $user_location='Paris';} else { }
                                                            echo $user_location;


                                                            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:



                                                            $a=10;
                                                            if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
                                                            echo $user_location;





                                                            share|improve this answer



























                                                              up vote
                                                              24
                                                              down vote













                                                              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:



                                                              $a=10;
                                                              if($a==5) { $user_location='Paris';} else { }
                                                              echo $user_location;


                                                              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:



                                                              $a=10;
                                                              if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
                                                              echo $user_location;





                                                              share|improve this answer

























                                                                up vote
                                                                24
                                                                down vote










                                                                up vote
                                                                24
                                                                down vote









                                                                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:



                                                                $a=10;
                                                                if($a==5) { $user_location='Paris';} else { }
                                                                echo $user_location;


                                                                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:



                                                                $a=10;
                                                                if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
                                                                echo $user_location;





                                                                share|improve this answer














                                                                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:



                                                                $a=10;
                                                                if($a==5) { $user_location='Paris';} else { }
                                                                echo $user_location;


                                                                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:



                                                                $a=10;
                                                                if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
                                                                echo $user_location;






                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Sep 22 '13 at 12:55


























                                                                community wiki





                                                                2 revs, 2 users 64%
                                                                Roger
























                                                                    up vote
                                                                    24
                                                                    down vote



                                                                    +25










                                                                    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 to display_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




                                                                    • .htconf (webserver configuration, including vhosts and sub-configurations)*

                                                                    • .htaccess

                                                                    • in php code itself


                                                                    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




                                                                    • Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.

                                                                    • Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed

                                                                    • Check error_reporting and display_errors php directives in .htaccess have not changed

                                                                    • If you have directive in .htaccess, check if they are still permitted in the .htconf file

                                                                    • Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.






                                                                    share|improve this answer



























                                                                      up vote
                                                                      24
                                                                      down vote



                                                                      +25










                                                                      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 to display_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




                                                                      • .htconf (webserver configuration, including vhosts and sub-configurations)*

                                                                      • .htaccess

                                                                      • in php code itself


                                                                      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




                                                                      • Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.

                                                                      • Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed

                                                                      • Check error_reporting and display_errors php directives in .htaccess have not changed

                                                                      • If you have directive in .htaccess, check if they are still permitted in the .htconf file

                                                                      • Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.






                                                                      share|improve this answer

























                                                                        up vote
                                                                        24
                                                                        down vote



                                                                        +25







                                                                        up vote
                                                                        24
                                                                        down vote



                                                                        +25




                                                                        +25




                                                                        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 to display_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




                                                                        • .htconf (webserver configuration, including vhosts and sub-configurations)*

                                                                        • .htaccess

                                                                        • in php code itself


                                                                        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




                                                                        • Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.

                                                                        • Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed

                                                                        • Check error_reporting and display_errors php directives in .htaccess have not changed

                                                                        • If you have directive in .htaccess, check if they are still permitted in the .htconf file

                                                                        • Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.






                                                                        share|improve this answer














                                                                        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 to display_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




                                                                        • .htconf (webserver configuration, including vhosts and sub-configurations)*

                                                                        • .htaccess

                                                                        • in php code itself


                                                                        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




                                                                        • Check error_reporting and display_errors php directives in php.ini has not changed, or that you're not using a different php.ini from before.

                                                                        • Check error_reporting and display_errors php directives in .htconf (or vhosts etc) have not changed

                                                                        • Check error_reporting and display_errors php directives in .htaccess have not changed

                                                                        • If you have directive in .htaccess, check if they are still permitted in the .htconf file

                                                                        • Finally check your code; possibly an unrelated library; to see if error_reporting and display_errors php directives have been set there.







                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        answered Nov 23 '16 at 1:44


























                                                                        community wiki





                                                                        Robbie























                                                                            up vote
                                                                            17
                                                                            down vote













                                                                            the quick fix is to assign your variable to null at the top of your code



                                                                            $user_location = null;





                                                                            share|improve this answer



























                                                                              up vote
                                                                              17
                                                                              down vote













                                                                              the quick fix is to assign your variable to null at the top of your code



                                                                              $user_location = null;





                                                                              share|improve this answer

























                                                                                up vote
                                                                                17
                                                                                down vote










                                                                                up vote
                                                                                17
                                                                                down vote









                                                                                the quick fix is to assign your variable to null at the top of your code



                                                                                $user_location = null;





                                                                                share|improve this answer














                                                                                the quick fix is to assign your variable to null at the top of your code



                                                                                $user_location = null;






                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                answered May 12 '14 at 19:02


























                                                                                community wiki





                                                                                Shahin Mammadzada























                                                                                    up vote
                                                                                    15
                                                                                    down vote













                                                                                    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:



                                                                                    // Echo whatever the hell this is
                                                                                    <?=$_POST['something']?>


                                                                                    ...Think again! A better solution is:



                                                                                    // If this is set, echo a filtered version
                                                                                    <?=isset($_POST['something']) ? html($_POST['something']) : ''?>


                                                                                    (I use a custom html() function to escape characters, your mileage may vary)






                                                                                    share|improve this answer



























                                                                                      up vote
                                                                                      15
                                                                                      down vote













                                                                                      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:



                                                                                      // Echo whatever the hell this is
                                                                                      <?=$_POST['something']?>


                                                                                      ...Think again! A better solution is:



                                                                                      // If this is set, echo a filtered version
                                                                                      <?=isset($_POST['something']) ? html($_POST['something']) : ''?>


                                                                                      (I use a custom html() function to escape characters, your mileage may vary)






                                                                                      share|improve this answer

























                                                                                        up vote
                                                                                        15
                                                                                        down vote










                                                                                        up vote
                                                                                        15
                                                                                        down vote









                                                                                        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:



                                                                                        // Echo whatever the hell this is
                                                                                        <?=$_POST['something']?>


                                                                                        ...Think again! A better solution is:



                                                                                        // If this is set, echo a filtered version
                                                                                        <?=isset($_POST['something']) ? html($_POST['something']) : ''?>


                                                                                        (I use a custom html() function to escape characters, your mileage may vary)






                                                                                        share|improve this answer














                                                                                        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:



                                                                                        // Echo whatever the hell this is
                                                                                        <?=$_POST['something']?>


                                                                                        ...Think again! A better solution is:



                                                                                        // If this is set, echo a filtered version
                                                                                        <?=isset($_POST['something']) ? html($_POST['something']) : ''?>


                                                                                        (I use a custom html() function to escape characters, your mileage may vary)







                                                                                        share|improve this answer














                                                                                        share|improve this answer



                                                                                        share|improve this answer








                                                                                        answered Jul 28 '15 at 19:12


























                                                                                        community wiki





                                                                                        rybo111























                                                                                            up vote
                                                                                            13
                                                                                            down vote













                                                                                            I use all time own useful function exst() which automatically declare variables.



                                                                                            Your code will be -



                                                                                            $greeting = "Hello, ".exst($user_name, 'Visitor')." from ".exst($user_location);


                                                                                            /**
                                                                                            * Function exst() - Checks if the variable has been set
                                                                                            * (copy/paste it in any place of your code)
                                                                                            *
                                                                                            * If the variable is set and not empty returns the variable (no transformation)
                                                                                            * If the variable is not set or empty, returns the $default value
                                                                                            *
                                                                                            * @param mixed $var
                                                                                            * @param mixed $default
                                                                                            *
                                                                                            * @return mixed
                                                                                            */

                                                                                            function exst( & $var, $default = "")
                                                                                            {
                                                                                            $t = "";
                                                                                            if ( !isset($var) || !$var ) {
                                                                                            if (isset($default) && $default != "") $t = $default;
                                                                                            }
                                                                                            else {
                                                                                            $t = $var;
                                                                                            }
                                                                                            if (is_string($t)) $t = trim($t);
                                                                                            return $t;
                                                                                            }





                                                                                            share|improve this answer



























                                                                                              up vote
                                                                                              13
                                                                                              down vote













                                                                                              I use all time own useful function exst() which automatically declare variables.



                                                                                              Your code will be -



                                                                                              $greeting = "Hello, ".exst($user_name, 'Visitor')." from ".exst($user_location);


                                                                                              /**
                                                                                              * Function exst() - Checks if the variable has been set
                                                                                              * (copy/paste it in any place of your code)
                                                                                              *
                                                                                              * If the variable is set and not empty returns the variable (no transformation)
                                                                                              * If the variable is not set or empty, returns the $default value
                                                                                              *
                                                                                              * @param mixed $var
                                                                                              * @param mixed $default
                                                                                              *
                                                                                              * @return mixed
                                                                                              */

                                                                                              function exst( & $var, $default = "")
                                                                                              {
                                                                                              $t = "";
                                                                                              if ( !isset($var) || !$var ) {
                                                                                              if (isset($default) && $default != "") $t = $default;
                                                                                              }
                                                                                              else {
                                                                                              $t = $var;
                                                                                              }
                                                                                              if (is_string($t)) $t = trim($t);
                                                                                              return $t;
                                                                                              }





                                                                                              share|improve this answer

























                                                                                                up vote
                                                                                                13
                                                                                                down vote










                                                                                                up vote
                                                                                                13
                                                                                                down vote









                                                                                                I use all time own useful function exst() which automatically declare variables.



                                                                                                Your code will be -



                                                                                                $greeting = "Hello, ".exst($user_name, 'Visitor')." from ".exst($user_location);


                                                                                                /**
                                                                                                * Function exst() - Checks if the variable has been set
                                                                                                * (copy/paste it in any place of your code)
                                                                                                *
                                                                                                * If the variable is set and not empty returns the variable (no transformation)
                                                                                                * If the variable is not set or empty, returns the $default value
                                                                                                *
                                                                                                * @param mixed $var
                                                                                                * @param mixed $default
                                                                                                *
                                                                                                * @return mixed
                                                                                                */

                                                                                                function exst( & $var, $default = "")
                                                                                                {
                                                                                                $t = "";
                                                                                                if ( !isset($var) || !$var ) {
                                                                                                if (isset($default) && $default != "") $t = $default;
                                                                                                }
                                                                                                else {
                                                                                                $t = $var;
                                                                                                }
                                                                                                if (is_string($t)) $t = trim($t);
                                                                                                return $t;
                                                                                                }





                                                                                                share|improve this answer














                                                                                                I use all time own useful function exst() which automatically declare variables.



                                                                                                Your code will be -



                                                                                                $greeting = "Hello, ".exst($user_name, 'Visitor')." from ".exst($user_location);


                                                                                                /**
                                                                                                * Function exst() - Checks if the variable has been set
                                                                                                * (copy/paste it in any place of your code)
                                                                                                *
                                                                                                * If the variable is set and not empty returns the variable (no transformation)
                                                                                                * If the variable is not set or empty, returns the $default value
                                                                                                *
                                                                                                * @param mixed $var
                                                                                                * @param mixed $default
                                                                                                *
                                                                                                * @return mixed
                                                                                                */

                                                                                                function exst( & $var, $default = "")
                                                                                                {
                                                                                                $t = "";
                                                                                                if ( !isset($var) || !$var ) {
                                                                                                if (isset($default) && $default != "") $t = $default;
                                                                                                }
                                                                                                else {
                                                                                                $t = $var;
                                                                                                }
                                                                                                if (is_string($t)) $t = trim($t);
                                                                                                return $t;
                                                                                                }






                                                                                                share|improve this answer














                                                                                                share|improve this answer



                                                                                                share|improve this answer








                                                                                                edited Apr 9 '13 at 14:07


























                                                                                                community wiki





                                                                                                2 revs
                                                                                                user2253362























                                                                                                    up vote
                                                                                                    13
                                                                                                    down vote













                                                                                                    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.




                                                                                                    share|improve this answer



























                                                                                                      up vote
                                                                                                      13
                                                                                                      down vote













                                                                                                      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.




                                                                                                      share|improve this answer

























                                                                                                        up vote
                                                                                                        13
                                                                                                        down vote










                                                                                                        up vote
                                                                                                        13
                                                                                                        down vote









                                                                                                        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.




                                                                                                        share|improve this answer














                                                                                                        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.





                                                                                                        share|improve this answer














                                                                                                        share|improve this answer



                                                                                                        share|improve this answer








                                                                                                        answered Dec 18 '15 at 11:06


























                                                                                                        community wiki





                                                                                                        Rishabh Seth























                                                                                                            up vote
                                                                                                            12
                                                                                                            down vote













                                                                                                            In PHP 7.0 it's now possible to use Null coalescing operator:



                                                                                                            echo "My index value is: " . ($my_array["my_index"] ?? '');


                                                                                                            Equals to:



                                                                                                            echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');


                                                                                                            PHP manual PHP 7.0






                                                                                                            share|improve this answer



















                                                                                                            • 1




                                                                                                              Wow, this answer needs to be voted up more now that this is available in PHP 7. Wonderful solution!!!
                                                                                                              – OCDev
                                                                                                              Sep 24 '17 at 13:17










                                                                                                            • This also works fine in if statements. if (is_array($my_array['idontexist'] ?? '')) { dosomething(); }
                                                                                                              – a coder
                                                                                                              Feb 23 at 20:04












                                                                                                            • Your code is actually a nice overlooked bug: ?? - only checks for isset(), if you pass is_array() - which is a boolean, unexpected behavior will follow.
                                                                                                              – Lachezar Lechev
                                                                                                              Feb 26 at 1:20

















                                                                                                            up vote
                                                                                                            12
                                                                                                            down vote













                                                                                                            In PHP 7.0 it's now possible to use Null coalescing operator:



                                                                                                            echo "My index value is: " . ($my_array["my_index"] ?? '');


                                                                                                            Equals to:



                                                                                                            echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');


                                                                                                            PHP manual PHP 7.0






                                                                                                            share|improve this answer



















                                                                                                            • 1




                                                                                                              Wow, this answer needs to be voted up more now that this is available in PHP 7. Wonderful solution!!!
                                                                                                              – OCDev
                                                                                                              Sep 24 '17 at 13:17










                                                                                                            • This also works fine in if statements. if (is_array($my_array['idontexist'] ?? '')) { dosomething(); }
                                                                                                              – a coder
                                                                                                              Feb 23 at 20:04












                                                                                                            • Your code is actually a nice overlooked bug: ?? - only checks for isset(), if you pass is_array() - which is a boolean, unexpected behavior will follow.
                                                                                                              – Lachezar Lechev
                                                                                                              Feb 26 at 1:20















                                                                                                            up vote
                                                                                                            12
                                                                                                            down vote










                                                                                                            up vote
                                                                                                            12
                                                                                                            down vote









                                                                                                            In PHP 7.0 it's now possible to use Null coalescing operator:



                                                                                                            echo "My index value is: " . ($my_array["my_index"] ?? '');


                                                                                                            Equals to:



                                                                                                            echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');


                                                                                                            PHP manual PHP 7.0






                                                                                                            share|improve this answer














                                                                                                            In PHP 7.0 it's now possible to use Null coalescing operator:



                                                                                                            echo "My index value is: " . ($my_array["my_index"] ?? '');


                                                                                                            Equals to:



                                                                                                            echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');


                                                                                                            PHP manual PHP 7.0







                                                                                                            share|improve this answer














                                                                                                            share|improve this answer



                                                                                                            share|improve this answer








                                                                                                            answered Dec 13 '16 at 13:34


























                                                                                                            community wiki





                                                                                                            Lachezar Lechev









                                                                                                            • 1




                                                                                                              Wow, this answer needs to be voted up more now that this is available in PHP 7. Wonderful solution!!!
                                                                                                              – OCDev
                                                                                                              Sep 24 '17 at 13:17










                                                                                                            • This also works fine in if statements. if (is_array($my_array['idontexist'] ?? '')) { dosomething(); }
                                                                                                              – a coder
                                                                                                              Feb 23 at 20:04












                                                                                                            • Your code is actually a nice overlooked bug: ?? - only checks for isset(), if you pass is_array() - which is a boolean, unexpected behavior will follow.
                                                                                                              – Lachezar Lechev
                                                                                                              Feb 26 at 1:20
















                                                                                                            • 1




                                                                                                              Wow, this answer needs to be voted up more now that this is available in PHP 7. Wonderful solution!!!
                                                                                                              – OCDev
                                                                                                              Sep 24 '17 at 13:17










                                                                                                            • This also works fine in if statements. if (is_array($my_array['idontexist'] ?? '')) { dosomething(); }
                                                                                                              – a coder
                                                                                                              Feb 23 at 20:04












                                                                                                            • Your code is actually a nice overlooked bug: ?? - only checks for isset(), if you pass is_array() - which is a boolean, unexpected behavior will follow.
                                                                                                              – Lachezar Lechev
                                                                                                              Feb 26 at 1:20










                                                                                                            1




                                                                                                            1




                                                                                                            Wow, this answer needs to be voted up more now that this is available in PHP 7. Wonderful solution!!!
                                                                                                            – OCDev
                                                                                                            Sep 24 '17 at 13:17




                                                                                                            Wow, this answer needs to be voted up more now that this is available in PHP 7. Wonderful solution!!!
                                                                                                            – OCDev
                                                                                                            Sep 24 '17 at 13:17












                                                                                                            This also works fine in if statements. if (is_array($my_array['idontexist'] ?? '')) { dosomething(); }
                                                                                                            – a coder
                                                                                                            Feb 23 at 20:04






                                                                                                            This also works fine in if statements. if (is_array($my_array['idontexist'] ?? '')) { dosomething(); }
                                                                                                            – a coder
                                                                                                            Feb 23 at 20:04














                                                                                                            Your code is actually a nice overlooked bug: ?? - only checks for isset(), if you pass is_array() - which is a boolean, unexpected behavior will follow.
                                                                                                            – Lachezar Lechev
                                                                                                            Feb 26 at 1:20






                                                                                                            Your code is actually a nice overlooked bug: ?? - only checks for isset(), if you pass is_array() - which is a boolean, unexpected behavior will follow.
                                                                                                            – Lachezar Lechev
                                                                                                            Feb 26 at 1:20












                                                                                                            up vote
                                                                                                            7
                                                                                                            down vote













                                                                                                            why not keep things simple?



                                                                                                            <?php
                                                                                                            error_reporting(E_ALL); // making sure all notices are on

                                                                                                            function idxVal(&$var, $default = null) {
                                                                                                            return empty($var) ? $var = $default : $var;
                                                                                                            }

                                                                                                            echo idxVal($arr['test']); // returns null without any notice
                                                                                                            echo idxVal($arr['hey ho'], 'yo'); // returns yo and assigns it to array index, nice

                                                                                                            ?>





                                                                                                            share|improve this answer



























                                                                                                              up vote
                                                                                                              7
                                                                                                              down vote













                                                                                                              why not keep things simple?



                                                                                                              <?php
                                                                                                              error_reporting(E_ALL); // making sure all notices are on

                                                                                                              function idxVal(&$var, $default = null) {
                                                                                                              return empty($var) ? $var = $default : $var;
                                                                                                              }

                                                                                                              echo idxVal($arr['test']); // returns null without any notice
                                                                                                              echo idxVal($arr['hey ho'], 'yo'); // returns yo and assigns it to array index, nice

                                                                                                              ?>





                                                                                                              share|improve this answer

























                                                                                                                up vote
                                                                                                                7
                                                                                                                down vote










                                                                                                                up vote
                                                                                                                7
                                                                                                                down vote









                                                                                                                why not keep things simple?



                                                                                                                <?php
                                                                                                                error_reporting(E_ALL); // making sure all notices are on

                                                                                                                function idxVal(&$var, $default = null) {
                                                                                                                return empty($var) ? $var = $default : $var;
                                                                                                                }

                                                                                                                echo idxVal($arr['test']); // returns null without any notice
                                                                                                                echo idxVal($arr['hey ho'], 'yo'); // returns yo and assigns it to array index, nice

                                                                                                                ?>





                                                                                                                share|improve this answer














                                                                                                                why not keep things simple?



                                                                                                                <?php
                                                                                                                error_reporting(E_ALL); // making sure all notices are on

                                                                                                                function idxVal(&$var, $default = null) {
                                                                                                                return empty($var) ? $var = $default : $var;
                                                                                                                }

                                                                                                                echo idxVal($arr['test']); // returns null without any notice
                                                                                                                echo idxVal($arr['hey ho'], 'yo'); // returns yo and assigns it to array index, nice

                                                                                                                ?>






                                                                                                                share|improve this answer














                                                                                                                share|improve this answer



                                                                                                                share|improve this answer








                                                                                                                answered Jun 6 '13 at 20:37


























                                                                                                                community wiki





                                                                                                                gts























                                                                                                                    up vote
                                                                                                                    7
                                                                                                                    down vote













                                                                                                                    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.



                                                                                                                    ; Common Values:
                                                                                                                    ; E_ALL (Show all errors, warnings and notices including coding standards.)
                                                                                                                    ; E_ALL & ~E_NOTICE (Show all errors, except for notices)
                                                                                                                    ; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
                                                                                                                    ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
                                                                                                                    ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
                                                                                                                    ; Development Value: E_ALL
                                                                                                                    ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
                                                                                                                    ; http://php.net/error-reporting
                                                                                                                    error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT


                                                                                                                    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:




                                                                                                                    1. You installed PHP and the new default settings are somewhat poorly documented, but do not exclude E_NOTICE.


                                                                                                                    2. 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, keeping E_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?




                                                                                                                    1. 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 in error_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.


                                                                                                                    2. 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 use php_value inside of <Directory>.


                                                                                                                    3. 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 and log_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.



                                                                                                                    function foo()
                                                                                                                    {
                                                                                                                    $my_variable_name = '';

                                                                                                                    //....

                                                                                                                    if ($my_variable_name) {
                                                                                                                    // perform some logic
                                                                                                                    }
                                                                                                                    }


                                                                                                                    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.



                                                                                                                    // verbose way - generally better
                                                                                                                    if (isset($my_array['my_index'])) {
                                                                                                                    echo "My index value is: " . $my_array['my_index'];
                                                                                                                    }

                                                                                                                    // non-verbose ternary example - I use this sometimes for small rules.
                                                                                                                    $my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
                                                                                                                    echo "My index value is: " . $my_index_val;


                                                                                                                    Another option is to declare an empty array at the top of your function. This is not always possible.



                                                                                                                    $my_array = array(
                                                                                                                    'my_index' => ''
                                                                                                                    );

                                                                                                                    //...

                                                                                                                    $my_array['my_index'] = 'new string';


                                                                                                                    (additional tip)




                                                                                                                    • When I was encountering these and other issues, I used NetBeans IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).






                                                                                                                    share|improve this answer



























                                                                                                                      up vote
                                                                                                                      7
                                                                                                                      down vote













                                                                                                                      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.



                                                                                                                      ; Common Values:
                                                                                                                      ; E_ALL (Show all errors, warnings and notices including coding standards.)
                                                                                                                      ; E_ALL & ~E_NOTICE (Show all errors, except for notices)
                                                                                                                      ; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
                                                                                                                      ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
                                                                                                                      ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
                                                                                                                      ; Development Value: E_ALL
                                                                                                                      ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
                                                                                                                      ; http://php.net/error-reporting
                                                                                                                      error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT


                                                                                                                      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:




                                                                                                                      1. You installed PHP and the new default settings are somewhat poorly documented, but do not exclude E_NOTICE.


                                                                                                                      2. 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, keeping E_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?




                                                                                                                      1. 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 in error_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.


                                                                                                                      2. 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 use php_value inside of <Directory>.


                                                                                                                      3. 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 and log_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.



                                                                                                                      function foo()
                                                                                                                      {
                                                                                                                      $my_variable_name = '';

                                                                                                                      //....

                                                                                                                      if ($my_variable_name) {
                                                                                                                      // perform some logic
                                                                                                                      }
                                                                                                                      }


                                                                                                                      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.



                                                                                                                      // verbose way - generally better
                                                                                                                      if (isset($my_array['my_index'])) {
                                                                                                                      echo "My index value is: " . $my_array['my_index'];
                                                                                                                      }

                                                                                                                      // non-verbose ternary example - I use this sometimes for small rules.
                                                                                                                      $my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
                                                                                                                      echo "My index value is: " . $my_index_val;


                                                                                                                      Another option is to declare an empty array at the top of your function. This is not always possible.



                                                                                                                      $my_array = array(
                                                                                                                      'my_index' => ''
                                                                                                                      );

                                                                                                                      //...

                                                                                                                      $my_array['my_index'] = 'new string';


                                                                                                                      (additional tip)




                                                                                                                      • When I was encountering these and other issues, I used NetBeans IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).






                                                                                                                      share|improve this answer

























                                                                                                                        up vote
                                                                                                                        7
                                                                                                                        down vote










                                                                                                                        up vote
                                                                                                                        7
                                                                                                                        down vote









                                                                                                                        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.



                                                                                                                        ; Common Values:
                                                                                                                        ; E_ALL (Show all errors, warnings and notices including coding standards.)
                                                                                                                        ; E_ALL & ~E_NOTICE (Show all errors, except for notices)
                                                                                                                        ; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
                                                                                                                        ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
                                                                                                                        ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
                                                                                                                        ; Development Value: E_ALL
                                                                                                                        ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
                                                                                                                        ; http://php.net/error-reporting
                                                                                                                        error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT


                                                                                                                        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:




                                                                                                                        1. You installed PHP and the new default settings are somewhat poorly documented, but do not exclude E_NOTICE.


                                                                                                                        2. 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, keeping E_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?




                                                                                                                        1. 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 in error_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.


                                                                                                                        2. 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 use php_value inside of <Directory>.


                                                                                                                        3. 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 and log_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.



                                                                                                                        function foo()
                                                                                                                        {
                                                                                                                        $my_variable_name = '';

                                                                                                                        //....

                                                                                                                        if ($my_variable_name) {
                                                                                                                        // perform some logic
                                                                                                                        }
                                                                                                                        }


                                                                                                                        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.



                                                                                                                        // verbose way - generally better
                                                                                                                        if (isset($my_array['my_index'])) {
                                                                                                                        echo "My index value is: " . $my_array['my_index'];
                                                                                                                        }

                                                                                                                        // non-verbose ternary example - I use this sometimes for small rules.
                                                                                                                        $my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
                                                                                                                        echo "My index value is: " . $my_index_val;


                                                                                                                        Another option is to declare an empty array at the top of your function. This is not always possible.



                                                                                                                        $my_array = array(
                                                                                                                        'my_index' => ''
                                                                                                                        );

                                                                                                                        //...

                                                                                                                        $my_array['my_index'] = 'new string';


                                                                                                                        (additional tip)




                                                                                                                        • When I was encountering these and other issues, I used NetBeans IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).






                                                                                                                        share|improve this answer














                                                                                                                        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.



                                                                                                                        ; Common Values:
                                                                                                                        ; E_ALL (Show all errors, warnings and notices including coding standards.)
                                                                                                                        ; E_ALL & ~E_NOTICE (Show all errors, except for notices)
                                                                                                                        ; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
                                                                                                                        ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
                                                                                                                        ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
                                                                                                                        ; Development Value: E_ALL
                                                                                                                        ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
                                                                                                                        ; http://php.net/error-reporting
                                                                                                                        error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT


                                                                                                                        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:




                                                                                                                        1. You installed PHP and the new default settings are somewhat poorly documented, but do not exclude E_NOTICE.


                                                                                                                        2. 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, keeping E_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?




                                                                                                                        1. 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 in error_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.


                                                                                                                        2. 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 use php_value inside of <Directory>.


                                                                                                                        3. 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 and log_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.



                                                                                                                        function foo()
                                                                                                                        {
                                                                                                                        $my_variable_name = '';

                                                                                                                        //....

                                                                                                                        if ($my_variable_name) {
                                                                                                                        // perform some logic
                                                                                                                        }
                                                                                                                        }


                                                                                                                        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.



                                                                                                                        // verbose way - generally better
                                                                                                                        if (isset($my_array['my_index'])) {
                                                                                                                        echo "My index value is: " . $my_array['my_index'];
                                                                                                                        }

                                                                                                                        // non-verbose ternary example - I use this sometimes for small rules.
                                                                                                                        $my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
                                                                                                                        echo "My index value is: " . $my_index_val;


                                                                                                                        Another option is to declare an empty array at the top of your function. This is not always possible.



                                                                                                                        $my_array = array(
                                                                                                                        'my_index' => ''
                                                                                                                        );

                                                                                                                        //...

                                                                                                                        $my_array['my_index'] = 'new string';


                                                                                                                        (additional tip)




                                                                                                                        • When I was encountering these and other issues, I used NetBeans IDE (free) and it gave me a host of warnings and notices. Some of them offer very helpful tips. This is not a requirement, and I don't use IDEs anymore except for large projects. I'm more of a vim person these days :).







                                                                                                                        share|improve this answer














                                                                                                                        share|improve this answer



                                                                                                                        share|improve this answer








                                                                                                                        answered Nov 28 '16 at 23:01


























                                                                                                                        community wiki





                                                                                                                        smcjones























                                                                                                                            up vote
                                                                                                                            5
                                                                                                                            down vote













                                                                                                                            undefined index means in an array you requested for unavailable array index for example



                                                                                                                            <?php 

                                                                                                                            $newArray = {1,2,3,4,5};
                                                                                                                            print_r($newArray[5]);

                                                                                                                            ?>


                                                                                                                            undefined variable means you have used completely not existing variable or which is not defined or initialized by that name for example



                                                                                                                            <?php print_r($myvar); ?>


                                                                                                                            undefined offset means in array you have asked for non existing key. And the
                                                                                                                            solution for this is to check before use



                                                                                                                            php> echo array_key_exists(1, $myarray);





                                                                                                                            share|improve this answer



























                                                                                                                              up vote
                                                                                                                              5
                                                                                                                              down vote













                                                                                                                              undefined index means in an array you requested for unavailable array index for example



                                                                                                                              <?php 

                                                                                                                              $newArray = {1,2,3,4,5};
                                                                                                                              print_r($newArray[5]);

                                                                                                                              ?>


                                                                                                                              undefined variable means you have used completely not existing variable or which is not defined or initialized by that name for example



                                                                                                                              <?php print_r($myvar); ?>


                                                                                                                              undefined offset means in array you have asked for non existing key. And the
                                                                                                                              solution for this is to check before use



                                                                                                                              php> echo array_key_exists(1, $myarray);





                                                                                                                              share|improve this answer

























                                                                                                                                up vote
                                                                                                                                5
                                                                                                                                down vote










                                                                                                                                up vote
                                                                                                                                5
                                                                                                                                down vote









                                                                                                                                undefined index means in an array you requested for unavailable array index for example



                                                                                                                                <?php 

                                                                                                                                $newArray = {1,2,3,4,5};
                                                                                                                                print_r($newArray[5]);

                                                                                                                                ?>


                                                                                                                                undefined variable means you have used completely not existing variable or which is not defined or initialized by that name for example



                                                                                                                                <?php print_r($myvar); ?>


                                                                                                                                undefined offset means in array you have asked for non existing key. And the
                                                                                                                                solution for this is to check before use



                                                                                                                                php> echo array_key_exists(1, $myarray);





                                                                                                                                share|improve this answer














                                                                                                                                undefined index means in an array you requested for unavailable array index for example



                                                                                                                                <?php 

                                                                                                                                $newArray = {1,2,3,4,5};
                                                                                                                                print_r($newArray[5]);

                                                                                                                                ?>


                                                                                                                                undefined variable means you have used completely not existing variable or which is not defined or initialized by that name for example



                                                                                                                                <?php print_r($myvar); ?>


                                                                                                                                undefined offset means in array you have asked for non existing key. And the
                                                                                                                                solution for this is to check before use



                                                                                                                                php> echo array_key_exists(1, $myarray);






                                                                                                                                share|improve this answer














                                                                                                                                share|improve this answer



                                                                                                                                share|improve this answer








                                                                                                                                edited Jun 30 '17 at 1:02


























                                                                                                                                community wiki





                                                                                                                                2 revs, 2 users 84%
                                                                                                                                Sintayehu Abaynhe























                                                                                                                                    up vote
                                                                                                                                    3
                                                                                                                                    down vote













                                                                                                                                    Regarding this part of the question:




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




                                                                                                                                    No definite answers but here are a some possible explanations of why settings can 'suddenly' change:




                                                                                                                                    1. You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.


                                                                                                                                    2. You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set() or error_reporting() (search for these in the code)


                                                                                                                                    3. You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.


                                                                                                                                    4. 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.







                                                                                                                                    share|improve this answer



























                                                                                                                                      up vote
                                                                                                                                      3
                                                                                                                                      down vote













                                                                                                                                      Regarding this part of the question:




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




                                                                                                                                      No definite answers but here are a some possible explanations of why settings can 'suddenly' change:




                                                                                                                                      1. You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.


                                                                                                                                      2. You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set() or error_reporting() (search for these in the code)


                                                                                                                                      3. You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.


                                                                                                                                      4. 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.







                                                                                                                                      share|improve this answer

























                                                                                                                                        up vote
                                                                                                                                        3
                                                                                                                                        down vote










                                                                                                                                        up vote
                                                                                                                                        3
                                                                                                                                        down vote









                                                                                                                                        Regarding this part of the question:




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




                                                                                                                                        No definite answers but here are a some possible explanations of why settings can 'suddenly' change:




                                                                                                                                        1. You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.


                                                                                                                                        2. You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set() or error_reporting() (search for these in the code)


                                                                                                                                        3. You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.


                                                                                                                                        4. 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.







                                                                                                                                        share|improve this answer














                                                                                                                                        Regarding this part of the question:




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




                                                                                                                                        No definite answers but here are a some possible explanations of why settings can 'suddenly' change:




                                                                                                                                        1. You have upgraded PHP to a newer version which can have other defaults for error_reporting, display_errors or other relevant settings.


                                                                                                                                        2. You have removed or introduced some code (possibly in a dependency) that sets relevant settings at runtime using ini_set() or error_reporting() (search for these in the code)


                                                                                                                                        3. You changed the webserver configuration (assuming apache here): .htaccess files and vhost configurations can also manipulate php settings.


                                                                                                                                        4. 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.








                                                                                                                                        share|improve this answer














                                                                                                                                        share|improve this answer



                                                                                                                                        share|improve this answer








                                                                                                                                        answered Nov 28 '16 at 19:31


























                                                                                                                                        community wiki





                                                                                                                                        Wouter de Winter























                                                                                                                                            up vote
                                                                                                                                            2
                                                                                                                                            down vote













                                                                                                                                            If working with classes you need to make sure you reference member variables using $this:



                                                                                                                                            class Person
                                                                                                                                            {
                                                                                                                                            protected $firstName;
                                                                                                                                            protected $lastName;

                                                                                                                                            public function setFullName($first, $last)
                                                                                                                                            {
                                                                                                                                            // Correct
                                                                                                                                            $this->firstName = $first;

                                                                                                                                            // Incorrect
                                                                                                                                            $lastName = $last;

                                                                                                                                            // Incorrect
                                                                                                                                            $this->$lastName = $last;
                                                                                                                                            }
                                                                                                                                            }





                                                                                                                                            share|improve this answer



























                                                                                                                                              up vote
                                                                                                                                              2
                                                                                                                                              down vote













                                                                                                                                              If working with classes you need to make sure you reference member variables using $this:



                                                                                                                                              class Person
                                                                                                                                              {
                                                                                                                                              protected $firstName;
                                                                                                                                              protected $lastName;

                                                                                                                                              public function setFullName($first, $last)
                                                                                                                                              {
                                                                                                                                              // Correct
                                                                                                                                              $this->firstName = $first;

                                                                                                                                              // Incorrect
                                                                                                                                              $lastName = $last;

                                                                                                                                              // Incorrect
                                                                                                                                              $this->$lastName = $last;
                                                                                                                                              }
                                                                                                                                              }





                                                                                                                                              share|improve this answer

























                                                                                                                                                up vote
                                                                                                                                                2
                                                                                                                                                down vote










                                                                                                                                                up vote
                                                                                                                                                2
                                                                                                                                                down vote









                                                                                                                                                If working with classes you need to make sure you reference member variables using $this:



                                                                                                                                                class Person
                                                                                                                                                {
                                                                                                                                                protected $firstName;
                                                                                                                                                protected $lastName;

                                                                                                                                                public function setFullName($first, $last)
                                                                                                                                                {
                                                                                                                                                // Correct
                                                                                                                                                $this->firstName = $first;

                                                                                                                                                // Incorrect
                                                                                                                                                $lastName = $last;

                                                                                                                                                // Incorrect
                                                                                                                                                $this->$lastName = $last;
                                                                                                                                                }
                                                                                                                                                }





                                                                                                                                                share|improve this answer














                                                                                                                                                If working with classes you need to make sure you reference member variables using $this:



                                                                                                                                                class Person
                                                                                                                                                {
                                                                                                                                                protected $firstName;
                                                                                                                                                protected $lastName;

                                                                                                                                                public function setFullName($first, $last)
                                                                                                                                                {
                                                                                                                                                // Correct
                                                                                                                                                $this->firstName = $first;

                                                                                                                                                // Incorrect
                                                                                                                                                $lastName = $last;

                                                                                                                                                // Incorrect
                                                                                                                                                $this->$lastName = $last;
                                                                                                                                                }
                                                                                                                                                }






                                                                                                                                                share|improve this answer














                                                                                                                                                share|improve this answer



                                                                                                                                                share|improve this answer








                                                                                                                                                edited Jul 20 '17 at 11:44


























                                                                                                                                                community wiki





                                                                                                                                                2 revs
                                                                                                                                                John Conde























                                                                                                                                                    up vote
                                                                                                                                                    2
                                                                                                                                                    down vote













                                                                                                                                                    Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.



                                                                                                                                                    I.e.:



                                                                                                                                                    $query = "SELECT col1 FROM table WHERE col_x = ?";


                                                                                                                                                    Then trying to access more columns/rows inside a loop.



                                                                                                                                                    I.e.:



                                                                                                                                                    print_r($row['col1']);
                                                                                                                                                    print_r($row['col2']); // undefined index thrown


                                                                                                                                                    or in a while loop:



                                                                                                                                                    while( $row = fetching_function($query) ) {

                                                                                                                                                    echo $row['col1'];
                                                                                                                                                    echo "<br>";
                                                                                                                                                    echo $row['col2']; // undefined index thrown
                                                                                                                                                    echo "<br>";
                                                                                                                                                    echo $row['col3']; // undefined index thrown

                                                                                                                                                    }


                                                                                                                                                    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







                                                                                                                                                    share|improve this answer























                                                                                                                                                    • I have to wonder why this was downvoted also.
                                                                                                                                                      – Funk Forty Niner
                                                                                                                                                      Oct 25 at 0:26















                                                                                                                                                    up vote
                                                                                                                                                    2
                                                                                                                                                    down vote













                                                                                                                                                    Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.



                                                                                                                                                    I.e.:



                                                                                                                                                    $query = "SELECT col1 FROM table WHERE col_x = ?";


                                                                                                                                                    Then trying to access more columns/rows inside a loop.



                                                                                                                                                    I.e.:



                                                                                                                                                    print_r($row['col1']);
                                                                                                                                                    print_r($row['col2']); // undefined index thrown


                                                                                                                                                    or in a while loop:



                                                                                                                                                    while( $row = fetching_function($query) ) {

                                                                                                                                                    echo $row['col1'];
                                                                                                                                                    echo "<br>";
                                                                                                                                                    echo $row['col2']; // undefined index thrown
                                                                                                                                                    echo "<br>";
                                                                                                                                                    echo $row['col3']; // undefined index thrown

                                                                                                                                                    }


                                                                                                                                                    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







                                                                                                                                                    share|improve this answer























                                                                                                                                                    • I have to wonder why this was downvoted also.
                                                                                                                                                      – Funk Forty Niner
                                                                                                                                                      Oct 25 at 0:26













                                                                                                                                                    up vote
                                                                                                                                                    2
                                                                                                                                                    down vote










                                                                                                                                                    up vote
                                                                                                                                                    2
                                                                                                                                                    down vote









                                                                                                                                                    Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.



                                                                                                                                                    I.e.:



                                                                                                                                                    $query = "SELECT col1 FROM table WHERE col_x = ?";


                                                                                                                                                    Then trying to access more columns/rows inside a loop.



                                                                                                                                                    I.e.:



                                                                                                                                                    print_r($row['col1']);
                                                                                                                                                    print_r($row['col2']); // undefined index thrown


                                                                                                                                                    or in a while loop:



                                                                                                                                                    while( $row = fetching_function($query) ) {

                                                                                                                                                    echo $row['col1'];
                                                                                                                                                    echo "<br>";
                                                                                                                                                    echo $row['col2']; // undefined index thrown
                                                                                                                                                    echo "<br>";
                                                                                                                                                    echo $row['col3']; // undefined index thrown

                                                                                                                                                    }


                                                                                                                                                    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







                                                                                                                                                    share|improve this answer














                                                                                                                                                    Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.



                                                                                                                                                    I.e.:



                                                                                                                                                    $query = "SELECT col1 FROM table WHERE col_x = ?";


                                                                                                                                                    Then trying to access more columns/rows inside a loop.



                                                                                                                                                    I.e.:



                                                                                                                                                    print_r($row['col1']);
                                                                                                                                                    print_r($row['col2']); // undefined index thrown


                                                                                                                                                    or in a while loop:



                                                                                                                                                    while( $row = fetching_function($query) ) {

                                                                                                                                                    echo $row['col1'];
                                                                                                                                                    echo "<br>";
                                                                                                                                                    echo $row['col2']; // undefined index thrown
                                                                                                                                                    echo "<br>";
                                                                                                                                                    echo $row['col3']; // undefined index thrown

                                                                                                                                                    }


                                                                                                                                                    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








                                                                                                                                                    share|improve this answer














                                                                                                                                                    share|improve this answer



                                                                                                                                                    share|improve this answer








                                                                                                                                                    edited Oct 25 '17 at 10:15


























                                                                                                                                                    community wiki





                                                                                                                                                    3 revs
                                                                                                                                                    Fred -ii-













                                                                                                                                                    • I have to wonder why this was downvoted also.
                                                                                                                                                      – Funk Forty Niner
                                                                                                                                                      Oct 25 at 0:26


















                                                                                                                                                    • I have to wonder why this was downvoted also.
                                                                                                                                                      – Funk Forty Niner
                                                                                                                                                      Oct 25 at 0:26
















                                                                                                                                                    I have to wonder why this was downvoted also.
                                                                                                                                                    – Funk Forty Niner
                                                                                                                                                    Oct 25 at 0:26




                                                                                                                                                    I have to wonder why this was downvoted also.
                                                                                                                                                    – Funk Forty Niner
                                                                                                                                                    Oct 25 at 0:26










                                                                                                                                                    up vote
                                                                                                                                                    1
                                                                                                                                                    down vote













                                                                                                                                                    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):



                                                                                                                                                    $newVariable = isset($thePotentialData) ? $thePotentialData : null;


                                                                                                                                                    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:



                                                                                                                                                    $newVariable = $thePotentialData ?? null;


                                                                                                                                                    Both will stop the Notices from the OP question, and both are the exact equivalent of:



                                                                                                                                                    if (isset($thePotentialData)) {
                                                                                                                                                    $newVariable = $thePotentialData;
                                                                                                                                                    } else {
                                                                                                                                                    $newVariable = null;
                                                                                                                                                    }


                                                                                                                                                     

                                                                                                                                                    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:



                                                                                                                                                    echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';


                                                                                                                                                    Function:



                                                                                                                                                    $foreName = getForeName(isset($userId) ? $userId : null);

                                                                                                                                                    function getForeName($userId)
                                                                                                                                                    {
                                                                                                                                                    if ($userId === null) {
                                                                                                                                                    // Etc
                                                                                                                                                    }
                                                                                                                                                    }


                                                                                                                                                    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.






                                                                                                                                                    share|improve this answer



























                                                                                                                                                      up vote
                                                                                                                                                      1
                                                                                                                                                      down vote













                                                                                                                                                      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):



                                                                                                                                                      $newVariable = isset($thePotentialData) ? $thePotentialData : null;


                                                                                                                                                      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:



                                                                                                                                                      $newVariable = $thePotentialData ?? null;


                                                                                                                                                      Both will stop the Notices from the OP question, and both are the exact equivalent of:



                                                                                                                                                      if (isset($thePotentialData)) {
                                                                                                                                                      $newVariable = $thePotentialData;
                                                                                                                                                      } else {
                                                                                                                                                      $newVariable = null;
                                                                                                                                                      }


                                                                                                                                                       

                                                                                                                                                      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:



                                                                                                                                                      echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';


                                                                                                                                                      Function:



                                                                                                                                                      $foreName = getForeName(isset($userId) ? $userId : null);

                                                                                                                                                      function getForeName($userId)
                                                                                                                                                      {
                                                                                                                                                      if ($userId === null) {
                                                                                                                                                      // Etc
                                                                                                                                                      }
                                                                                                                                                      }


                                                                                                                                                      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.






                                                                                                                                                      share|improve this answer

























                                                                                                                                                        up vote
                                                                                                                                                        1
                                                                                                                                                        down vote










                                                                                                                                                        up vote
                                                                                                                                                        1
                                                                                                                                                        down vote









                                                                                                                                                        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):



                                                                                                                                                        $newVariable = isset($thePotentialData) ? $thePotentialData : null;


                                                                                                                                                        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:



                                                                                                                                                        $newVariable = $thePotentialData ?? null;


                                                                                                                                                        Both will stop the Notices from the OP question, and both are the exact equivalent of:



                                                                                                                                                        if (isset($thePotentialData)) {
                                                                                                                                                        $newVariable = $thePotentialData;
                                                                                                                                                        } else {
                                                                                                                                                        $newVariable = null;
                                                                                                                                                        }


                                                                                                                                                         

                                                                                                                                                        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:



                                                                                                                                                        echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';


                                                                                                                                                        Function:



                                                                                                                                                        $foreName = getForeName(isset($userId) ? $userId : null);

                                                                                                                                                        function getForeName($userId)
                                                                                                                                                        {
                                                                                                                                                        if ($userId === null) {
                                                                                                                                                        // Etc
                                                                                                                                                        }
                                                                                                                                                        }


                                                                                                                                                        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.






                                                                                                                                                        share|improve this answer














                                                                                                                                                        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):



                                                                                                                                                        $newVariable = isset($thePotentialData) ? $thePotentialData : null;


                                                                                                                                                        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:



                                                                                                                                                        $newVariable = $thePotentialData ?? null;


                                                                                                                                                        Both will stop the Notices from the OP question, and both are the exact equivalent of:



                                                                                                                                                        if (isset($thePotentialData)) {
                                                                                                                                                        $newVariable = $thePotentialData;
                                                                                                                                                        } else {
                                                                                                                                                        $newVariable = null;
                                                                                                                                                        }


                                                                                                                                                         

                                                                                                                                                        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:



                                                                                                                                                        echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';


                                                                                                                                                        Function:



                                                                                                                                                        $foreName = getForeName(isset($userId) ? $userId : null);

                                                                                                                                                        function getForeName($userId)
                                                                                                                                                        {
                                                                                                                                                        if ($userId === null) {
                                                                                                                                                        // Etc
                                                                                                                                                        }
                                                                                                                                                        }


                                                                                                                                                        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.







                                                                                                                                                        share|improve this answer














                                                                                                                                                        share|improve this answer



                                                                                                                                                        share|improve this answer








                                                                                                                                                        answered Jul 6 at 18:56


























                                                                                                                                                        community wiki





                                                                                                                                                        James























                                                                                                                                                            up vote
                                                                                                                                                            0
                                                                                                                                                            down vote













                                                                                                                                                            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.






                                                                                                                                                            share|improve this answer



























                                                                                                                                                              up vote
                                                                                                                                                              0
                                                                                                                                                              down vote













                                                                                                                                                              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.






                                                                                                                                                              share|improve this answer

























                                                                                                                                                                up vote
                                                                                                                                                                0
                                                                                                                                                                down vote










                                                                                                                                                                up vote
                                                                                                                                                                0
                                                                                                                                                                down vote









                                                                                                                                                                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.






                                                                                                                                                                share|improve this answer














                                                                                                                                                                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.







                                                                                                                                                                share|improve this answer














                                                                                                                                                                share|improve this answer



                                                                                                                                                                share|improve this answer








                                                                                                                                                                answered Aug 30 '17 at 9:08


























                                                                                                                                                                community wiki





                                                                                                                                                                phvish























                                                                                                                                                                    up vote
                                                                                                                                                                    0
                                                                                                                                                                    down vote













                                                                                                                                                                    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



                                                                                                                                                                    <!-- The data encoding type, enctype, MUST be specified as below -->
                                                                                                                                                                    <form enctype="multipart/form-data" action="__URL__" method="POST">
                                                                                                                                                                    <!-- MAX_FILE_SIZE must precede the file input field -->
                                                                                                                                                                    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
                                                                                                                                                                    <!-- Name of input element determines name in $_FILES array -->
                                                                                                                                                                    Send this file: <input name="userfile" type="file" />
                                                                                                                                                                    <input type="submit" value="Send File" />
                                                                                                                                                                    </form>


                                                                                                                                                                    PHP



                                                                                                                                                                    <?php
                                                                                                                                                                    // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
                                                                                                                                                                    // of $_FILES.

                                                                                                                                                                    $uploaddir = '/var/www/uploads/';
                                                                                                                                                                    $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

                                                                                                                                                                    echo '<pre>';
                                                                                                                                                                    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                                                                                                                                                                    echo "File is valid, and was successfully uploaded.n";
                                                                                                                                                                    } else {
                                                                                                                                                                    echo "Possible file upload attack!n";
                                                                                                                                                                    }

                                                                                                                                                                    echo 'Here is some more debugging info:';
                                                                                                                                                                    print_r($_FILES);

                                                                                                                                                                    print "</pre>";

                                                                                                                                                                    ?>


                                                                                                                                                                    Reference:




                                                                                                                                                                    • http://php.net/manual/en/features.file-upload.post-method.php






                                                                                                                                                                    share|improve this answer



























                                                                                                                                                                      up vote
                                                                                                                                                                      0
                                                                                                                                                                      down vote













                                                                                                                                                                      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



                                                                                                                                                                      <!-- The data encoding type, enctype, MUST be specified as below -->
                                                                                                                                                                      <form enctype="multipart/form-data" action="__URL__" method="POST">
                                                                                                                                                                      <!-- MAX_FILE_SIZE must precede the file input field -->
                                                                                                                                                                      <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
                                                                                                                                                                      <!-- Name of input element determines name in $_FILES array -->
                                                                                                                                                                      Send this file: <input name="userfile" type="file" />
                                                                                                                                                                      <input type="submit" value="Send File" />
                                                                                                                                                                      </form>


                                                                                                                                                                      PHP



                                                                                                                                                                      <?php
                                                                                                                                                                      // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
                                                                                                                                                                      // of $_FILES.

                                                                                                                                                                      $uploaddir = '/var/www/uploads/';
                                                                                                                                                                      $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

                                                                                                                                                                      echo '<pre>';
                                                                                                                                                                      if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                                                                                                                                                                      echo "File is valid, and was successfully uploaded.n";
                                                                                                                                                                      } else {
                                                                                                                                                                      echo "Possible file upload attack!n";
                                                                                                                                                                      }

                                                                                                                                                                      echo 'Here is some more debugging info:';
                                                                                                                                                                      print_r($_FILES);

                                                                                                                                                                      print "</pre>";

                                                                                                                                                                      ?>


                                                                                                                                                                      Reference:




                                                                                                                                                                      • http://php.net/manual/en/features.file-upload.post-method.php






                                                                                                                                                                      share|improve this answer

























                                                                                                                                                                        up vote
                                                                                                                                                                        0
                                                                                                                                                                        down vote










                                                                                                                                                                        up vote
                                                                                                                                                                        0
                                                                                                                                                                        down vote









                                                                                                                                                                        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



                                                                                                                                                                        <!-- The data encoding type, enctype, MUST be specified as below -->
                                                                                                                                                                        <form enctype="multipart/form-data" action="__URL__" method="POST">
                                                                                                                                                                        <!-- MAX_FILE_SIZE must precede the file input field -->
                                                                                                                                                                        <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
                                                                                                                                                                        <!-- Name of input element determines name in $_FILES array -->
                                                                                                                                                                        Send this file: <input name="userfile" type="file" />
                                                                                                                                                                        <input type="submit" value="Send File" />
                                                                                                                                                                        </form>


                                                                                                                                                                        PHP



                                                                                                                                                                        <?php
                                                                                                                                                                        // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
                                                                                                                                                                        // of $_FILES.

                                                                                                                                                                        $uploaddir = '/var/www/uploads/';
                                                                                                                                                                        $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

                                                                                                                                                                        echo '<pre>';
                                                                                                                                                                        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                                                                                                                                                                        echo "File is valid, and was successfully uploaded.n";
                                                                                                                                                                        } else {
                                                                                                                                                                        echo "Possible file upload attack!n";
                                                                                                                                                                        }

                                                                                                                                                                        echo 'Here is some more debugging info:';
                                                                                                                                                                        print_r($_FILES);

                                                                                                                                                                        print "</pre>";

                                                                                                                                                                        ?>


                                                                                                                                                                        Reference:




                                                                                                                                                                        • http://php.net/manual/en/features.file-upload.post-method.php






                                                                                                                                                                        share|improve this answer














                                                                                                                                                                        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



                                                                                                                                                                        <!-- The data encoding type, enctype, MUST be specified as below -->
                                                                                                                                                                        <form enctype="multipart/form-data" action="__URL__" method="POST">
                                                                                                                                                                        <!-- MAX_FILE_SIZE must precede the file input field -->
                                                                                                                                                                        <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
                                                                                                                                                                        <!-- Name of input element determines name in $_FILES array -->
                                                                                                                                                                        Send this file: <input name="userfile" type="file" />
                                                                                                                                                                        <input type="submit" value="Send File" />
                                                                                                                                                                        </form>


                                                                                                                                                                        PHP



                                                                                                                                                                        <?php
                                                                                                                                                                        // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
                                                                                                                                                                        // of $_FILES.

                                                                                                                                                                        $uploaddir = '/var/www/uploads/';
                                                                                                                                                                        $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

                                                                                                                                                                        echo '<pre>';
                                                                                                                                                                        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                                                                                                                                                                        echo "File is valid, and was successfully uploaded.n";
                                                                                                                                                                        } else {
                                                                                                                                                                        echo "Possible file upload attack!n";
                                                                                                                                                                        }

                                                                                                                                                                        echo 'Here is some more debugging info:';
                                                                                                                                                                        print_r($_FILES);

                                                                                                                                                                        print "</pre>";

                                                                                                                                                                        ?>


                                                                                                                                                                        Reference:




                                                                                                                                                                        • http://php.net/manual/en/features.file-upload.post-method.php







                                                                                                                                                                        share|improve this answer














                                                                                                                                                                        share|improve this answer



                                                                                                                                                                        share|improve this answer








                                                                                                                                                                        answered Oct 7 '17 at 12:21


























                                                                                                                                                                        community wiki





                                                                                                                                                                        Funk Forty Niner























                                                                                                                                                                            up vote
                                                                                                                                                                            0
                                                                                                                                                                            down vote













                                                                                                                                                                            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>



                                                                                                                                                                            <form action="example.php" method="post">
                                                                                                                                                                            <p>
                                                                                                                                                                            <input type="text" name="name" />
                                                                                                                                                                            <input type="submit" value="Submit" />
                                                                                                                                                                            </p>
                                                                                                                                                                            </form>

                                                                                                                                                                            <select name="choice">
                                                                                                                                                                            <option value="choice1">choice 1</option>
                                                                                                                                                                            <option value="choice2">choice 2</option>
                                                                                                                                                                            <option value="choice3">choice 3</option>
                                                                                                                                                                            <option value="choice4">choice 4</option>
                                                                                                                                                                            </select>


                                                                                                                                                                            Example: Element now contained within the <form>



                                                                                                                                                                            <form action="example.php" method="post">
                                                                                                                                                                            <select name="choice">
                                                                                                                                                                            <option value="choice1">choice 1</option>
                                                                                                                                                                            <option value="choice2">choice 2</option>
                                                                                                                                                                            <option value="choice3">choice 3</option>
                                                                                                                                                                            <option value="choice4">choice 4</option>
                                                                                                                                                                            </select>
                                                                                                                                                                            <p>
                                                                                                                                                                            <input type="text" name="name" />
                                                                                                                                                                            <input type="submit" value="Submit" />
                                                                                                                                                                            </p>
                                                                                                                                                                            </form>





                                                                                                                                                                            share|improve this answer



























                                                                                                                                                                              up vote
                                                                                                                                                                              0
                                                                                                                                                                              down vote













                                                                                                                                                                              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>



                                                                                                                                                                              <form action="example.php" method="post">
                                                                                                                                                                              <p>
                                                                                                                                                                              <input type="text" name="name" />
                                                                                                                                                                              <input type="submit" value="Submit" />
                                                                                                                                                                              </p>
                                                                                                                                                                              </form>

                                                                                                                                                                              <select name="choice">
                                                                                                                                                                              <option value="choice1">choice 1</option>
                                                                                                                                                                              <option value="choice2">choice 2</option>
                                                                                                                                                                              <option value="choice3">choice 3</option>
                                                                                                                                                                              <option value="choice4">choice 4</option>
                                                                                                                                                                              </select>


                                                                                                                                                                              Example: Element now contained within the <form>



                                                                                                                                                                              <form action="example.php" method="post">
                                                                                                                                                                              <select name="choice">
                                                                                                                                                                              <option value="choice1">choice 1</option>
                                                                                                                                                                              <option value="choice2">choice 2</option>
                                                                                                                                                                              <option value="choice3">choice 3</option>
                                                                                                                                                                              <option value="choice4">choice 4</option>
                                                                                                                                                                              </select>
                                                                                                                                                                              <p>
                                                                                                                                                                              <input type="text" name="name" />
                                                                                                                                                                              <input type="submit" value="Submit" />
                                                                                                                                                                              </p>
                                                                                                                                                                              </form>





                                                                                                                                                                              share|improve this answer

























                                                                                                                                                                                up vote
                                                                                                                                                                                0
                                                                                                                                                                                down vote










                                                                                                                                                                                up vote
                                                                                                                                                                                0
                                                                                                                                                                                down vote









                                                                                                                                                                                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>



                                                                                                                                                                                <form action="example.php" method="post">
                                                                                                                                                                                <p>
                                                                                                                                                                                <input type="text" name="name" />
                                                                                                                                                                                <input type="submit" value="Submit" />
                                                                                                                                                                                </p>
                                                                                                                                                                                </form>

                                                                                                                                                                                <select name="choice">
                                                                                                                                                                                <option value="choice1">choice 1</option>
                                                                                                                                                                                <option value="choice2">choice 2</option>
                                                                                                                                                                                <option value="choice3">choice 3</option>
                                                                                                                                                                                <option value="choice4">choice 4</option>
                                                                                                                                                                                </select>


                                                                                                                                                                                Example: Element now contained within the <form>



                                                                                                                                                                                <form action="example.php" method="post">
                                                                                                                                                                                <select name="choice">
                                                                                                                                                                                <option value="choice1">choice 1</option>
                                                                                                                                                                                <option value="choice2">choice 2</option>
                                                                                                                                                                                <option value="choice3">choice 3</option>
                                                                                                                                                                                <option value="choice4">choice 4</option>
                                                                                                                                                                                </select>
                                                                                                                                                                                <p>
                                                                                                                                                                                <input type="text" name="name" />
                                                                                                                                                                                <input type="submit" value="Submit" />
                                                                                                                                                                                </p>
                                                                                                                                                                                </form>





                                                                                                                                                                                share|improve this answer














                                                                                                                                                                                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>



                                                                                                                                                                                <form action="example.php" method="post">
                                                                                                                                                                                <p>
                                                                                                                                                                                <input type="text" name="name" />
                                                                                                                                                                                <input type="submit" value="Submit" />
                                                                                                                                                                                </p>
                                                                                                                                                                                </form>

                                                                                                                                                                                <select name="choice">
                                                                                                                                                                                <option value="choice1">choice 1</option>
                                                                                                                                                                                <option value="choice2">choice 2</option>
                                                                                                                                                                                <option value="choice3">choice 3</option>
                                                                                                                                                                                <option value="choice4">choice 4</option>
                                                                                                                                                                                </select>


                                                                                                                                                                                Example: Element now contained within the <form>



                                                                                                                                                                                <form action="example.php" method="post">
                                                                                                                                                                                <select name="choice">
                                                                                                                                                                                <option value="choice1">choice 1</option>
                                                                                                                                                                                <option value="choice2">choice 2</option>
                                                                                                                                                                                <option value="choice3">choice 3</option>
                                                                                                                                                                                <option value="choice4">choice 4</option>
                                                                                                                                                                                </select>
                                                                                                                                                                                <p>
                                                                                                                                                                                <input type="text" name="name" />
                                                                                                                                                                                <input type="submit" value="Submit" />
                                                                                                                                                                                </p>
                                                                                                                                                                                </form>






                                                                                                                                                                                share|improve this answer














                                                                                                                                                                                share|improve this answer



                                                                                                                                                                                share|improve this answer








                                                                                                                                                                                answered Jul 5 at 20:46


























                                                                                                                                                                                community wiki





                                                                                                                                                                                John Conde























                                                                                                                                                                                    up vote
                                                                                                                                                                                    0
                                                                                                                                                                                    down vote













                                                                                                                                                                                    I asked a question about this and I was referred to this post with the message:




                                                                                                                                                                                    This question already has an answer here:



                                                                                                                                                                                    “Notice: Undefined variable”, “Notice: Undefined index”, and “Notice:
                                                                                                                                                                                    Undefined offset” using PHP




                                                                                                                                                                                    I am sharing my question and solution here:



                                                                                                                                                                                    This is the error:



                                                                                                                                                                                    enter image description here



                                                                                                                                                                                    Line 154 is the problem. This is what I have in line 154:



                                                                                                                                                                                    153    foreach($cities as $key => $city){
                                                                                                                                                                                    154 if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){


                                                                                                                                                                                    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():



                                                                                                                                                                                    foreach($cities as $key => $city){
                                                                                                                                                                                    if(array_key_exists($key, $citiesCounterArray)){
                                                                                                                                                                                    if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){





                                                                                                                                                                                    share|improve this answer



























                                                                                                                                                                                      up vote
                                                                                                                                                                                      0
                                                                                                                                                                                      down vote













                                                                                                                                                                                      I asked a question about this and I was referred to this post with the message:




                                                                                                                                                                                      This question already has an answer here:



                                                                                                                                                                                      “Notice: Undefined variable”, “Notice: Undefined index”, and “Notice:
                                                                                                                                                                                      Undefined offset” using PHP




                                                                                                                                                                                      I am sharing my question and solution here:



                                                                                                                                                                                      This is the error:



                                                                                                                                                                                      enter image description here



                                                                                                                                                                                      Line 154 is the problem. This is what I have in line 154:



                                                                                                                                                                                      153    foreach($cities as $key => $city){
                                                                                                                                                                                      154 if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){


                                                                                                                                                                                      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():



                                                                                                                                                                                      foreach($cities as $key => $city){
                                                                                                                                                                                      if(array_key_exists($key, $citiesCounterArray)){
                                                                                                                                                                                      if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){





                                                                                                                                                                                      share|improve this answer

























                                                                                                                                                                                        up vote
                                                                                                                                                                                        0
                                                                                                                                                                                        down vote










                                                                                                                                                                                        up vote
                                                                                                                                                                                        0
                                                                                                                                                                                        down vote









                                                                                                                                                                                        I asked a question about this and I was referred to this post with the message:




                                                                                                                                                                                        This question already has an answer here:



                                                                                                                                                                                        “Notice: Undefined variable”, “Notice: Undefined index”, and “Notice:
                                                                                                                                                                                        Undefined offset” using PHP




                                                                                                                                                                                        I am sharing my question and solution here:



                                                                                                                                                                                        This is the error:



                                                                                                                                                                                        enter image description here



                                                                                                                                                                                        Line 154 is the problem. This is what I have in line 154:



                                                                                                                                                                                        153    foreach($cities as $key => $city){
                                                                                                                                                                                        154 if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){


                                                                                                                                                                                        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():



                                                                                                                                                                                        foreach($cities as $key => $city){
                                                                                                                                                                                        if(array_key_exists($key, $citiesCounterArray)){
                                                                                                                                                                                        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){





                                                                                                                                                                                        share|improve this answer














                                                                                                                                                                                        I asked a question about this and I was referred to this post with the message:




                                                                                                                                                                                        This question already has an answer here:



                                                                                                                                                                                        “Notice: Undefined variable”, “Notice: Undefined index”, and “Notice:
                                                                                                                                                                                        Undefined offset” using PHP




                                                                                                                                                                                        I am sharing my question and solution here:



                                                                                                                                                                                        This is the error:



                                                                                                                                                                                        enter image description here



                                                                                                                                                                                        Line 154 is the problem. This is what I have in line 154:



                                                                                                                                                                                        153    foreach($cities as $key => $city){
                                                                                                                                                                                        154 if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){


                                                                                                                                                                                        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():



                                                                                                                                                                                        foreach($cities as $key => $city){
                                                                                                                                                                                        if(array_key_exists($key, $citiesCounterArray)){
                                                                                                                                                                                        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){






                                                                                                                                                                                        share|improve this answer














                                                                                                                                                                                        share|improve this answer



                                                                                                                                                                                        share|improve this answer








                                                                                                                                                                                        answered Sep 1 at 18:31


























                                                                                                                                                                                        community wiki





                                                                                                                                                                                        Jaime Montoya























                                                                                                                                                                                            up vote
                                                                                                                                                                                            0
                                                                                                                                                                                            down vote













                                                                                                                                                                                            Different type of errors



                                                                                                                                                                                            1)Notice: Undefined variable




                                                                                                                                                                                            You will get this error if you have not define the variable and you
                                                                                                                                                                                            are trying to access or use that variable.




                                                                                                                                                                                            Example:



                                                                                                                                                                                                <?php
                                                                                                                                                                                            echo $a;
                                                                                                                                                                                            ?>

                                                                                                                                                                                            Notice: Undefined variable: a


                                                                                                                                                                                            2)Notice: Undefined index & Undefined offset




                                                                                                                                                                                            It means you're referring to an array key that doesn't exist. "Offset"



                                                                                                                                                                                            refers to the integer key of a numeric array, and "index" refers to
                                                                                                                                                                                            the



                                                                                                                                                                                            string key of an associative array.




                                                                                                                                                                                            <?php 
                                                                                                                                                                                            $testArr=array("Test1", "Test2");

                                                                                                                                                                                            print $testArr[2]; //undefined offset

                                                                                                                                                                                            $myArr=array("val1"=>"1", "val2"=>"2");

                                                                                                                                                                                            print $myArr['val3']; //undefined index
                                                                                                                                                                                            ?>





                                                                                                                                                                                            share|improve this answer



























                                                                                                                                                                                              up vote
                                                                                                                                                                                              0
                                                                                                                                                                                              down vote













                                                                                                                                                                                              Different type of errors



                                                                                                                                                                                              1)Notice: Undefined variable




                                                                                                                                                                                              You will get this error if you have not define the variable and you
                                                                                                                                                                                              are trying to access or use that variable.




                                                                                                                                                                                              Example:



                                                                                                                                                                                                  <?php
                                                                                                                                                                                              echo $a;
                                                                                                                                                                                              ?>

                                                                                                                                                                                              Notice: Undefined variable: a


                                                                                                                                                                                              2)Notice: Undefined index & Undefined offset




                                                                                                                                                                                              It means you're referring to an array key that doesn't exist. "Offset"



                                                                                                                                                                                              refers to the integer key of a numeric array, and "index" refers to
                                                                                                                                                                                              the



                                                                                                                                                                                              string key of an associative array.




                                                                                                                                                                                              <?php 
                                                                                                                                                                                              $testArr=array("Test1", "Test2");

                                                                                                                                                                                              print $testArr[2]; //undefined offset

                                                                                                                                                                                              $myArr=array("val1"=>"1", "val2"=>"2");

                                                                                                                                                                                              print $myArr['val3']; //undefined index
                                                                                                                                                                                              ?>





                                                                                                                                                                                              share|improve this answer

























                                                                                                                                                                                                up vote
                                                                                                                                                                                                0
                                                                                                                                                                                                down vote










                                                                                                                                                                                                up vote
                                                                                                                                                                                                0
                                                                                                                                                                                                down vote









                                                                                                                                                                                                Different type of errors



                                                                                                                                                                                                1)Notice: Undefined variable




                                                                                                                                                                                                You will get this error if you have not define the variable and you
                                                                                                                                                                                                are trying to access or use that variable.




                                                                                                                                                                                                Example:



                                                                                                                                                                                                    <?php
                                                                                                                                                                                                echo $a;
                                                                                                                                                                                                ?>

                                                                                                                                                                                                Notice: Undefined variable: a


                                                                                                                                                                                                2)Notice: Undefined index & Undefined offset




                                                                                                                                                                                                It means you're referring to an array key that doesn't exist. "Offset"



                                                                                                                                                                                                refers to the integer key of a numeric array, and "index" refers to
                                                                                                                                                                                                the



                                                                                                                                                                                                string key of an associative array.




                                                                                                                                                                                                <?php 
                                                                                                                                                                                                $testArr=array("Test1", "Test2");

                                                                                                                                                                                                print $testArr[2]; //undefined offset

                                                                                                                                                                                                $myArr=array("val1"=>"1", "val2"=>"2");

                                                                                                                                                                                                print $myArr['val3']; //undefined index
                                                                                                                                                                                                ?>





                                                                                                                                                                                                share|improve this answer














                                                                                                                                                                                                Different type of errors



                                                                                                                                                                                                1)Notice: Undefined variable




                                                                                                                                                                                                You will get this error if you have not define the variable and you
                                                                                                                                                                                                are trying to access or use that variable.




                                                                                                                                                                                                Example:



                                                                                                                                                                                                    <?php
                                                                                                                                                                                                echo $a;
                                                                                                                                                                                                ?>

                                                                                                                                                                                                Notice: Undefined variable: a


                                                                                                                                                                                                2)Notice: Undefined index & Undefined offset




                                                                                                                                                                                                It means you're referring to an array key that doesn't exist. "Offset"



                                                                                                                                                                                                refers to the integer key of a numeric array, and "index" refers to
                                                                                                                                                                                                the



                                                                                                                                                                                                string key of an associative array.




                                                                                                                                                                                                <?php 
                                                                                                                                                                                                $testArr=array("Test1", "Test2");

                                                                                                                                                                                                print $testArr[2]; //undefined offset

                                                                                                                                                                                                $myArr=array("val1"=>"1", "val2"=>"2");

                                                                                                                                                                                                print $myArr['val3']; //undefined index
                                                                                                                                                                                                ?>






                                                                                                                                                                                                share|improve this answer














                                                                                                                                                                                                share|improve this answer



                                                                                                                                                                                                share|improve this answer








                                                                                                                                                                                                answered Nov 9 at 11:00


























                                                                                                                                                                                                community wiki





                                                                                                                                                                                                bhanu sengar























                                                                                                                                                                                                    up vote
                                                                                                                                                                                                    -1
                                                                                                                                                                                                    down vote













                                                                                                                                                                                                    Those notices are because you don't have the used variable defined and my_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:



                                                                                                                                                                                                    $my_variable_name = "Variable name"; // defining variable
                                                                                                                                                                                                    echo "My variable value is: " . $my_variable_name;

                                                                                                                                                                                                    if(isset($my_array["my_index"])){
                                                                                                                                                                                                    echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
                                                                                                                                                                                                    }


                                                                                                                                                                                                    Another way to get this out:



                                                                                                                                                                                                    ini_set("error_reporting", false)





                                                                                                                                                                                                    share|improve this answer



























                                                                                                                                                                                                      up vote
                                                                                                                                                                                                      -1
                                                                                                                                                                                                      down vote













                                                                                                                                                                                                      Those notices are because you don't have the used variable defined and my_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:



                                                                                                                                                                                                      $my_variable_name = "Variable name"; // defining variable
                                                                                                                                                                                                      echo "My variable value is: " . $my_variable_name;

                                                                                                                                                                                                      if(isset($my_array["my_index"])){
                                                                                                                                                                                                      echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
                                                                                                                                                                                                      }


                                                                                                                                                                                                      Another way to get this out:



                                                                                                                                                                                                      ini_set("error_reporting", false)





                                                                                                                                                                                                      share|improve this answer

























                                                                                                                                                                                                        up vote
                                                                                                                                                                                                        -1
                                                                                                                                                                                                        down vote










                                                                                                                                                                                                        up vote
                                                                                                                                                                                                        -1
                                                                                                                                                                                                        down vote









                                                                                                                                                                                                        Those notices are because you don't have the used variable defined and my_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:



                                                                                                                                                                                                        $my_variable_name = "Variable name"; // defining variable
                                                                                                                                                                                                        echo "My variable value is: " . $my_variable_name;

                                                                                                                                                                                                        if(isset($my_array["my_index"])){
                                                                                                                                                                                                        echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
                                                                                                                                                                                                        }


                                                                                                                                                                                                        Another way to get this out:



                                                                                                                                                                                                        ini_set("error_reporting", false)





                                                                                                                                                                                                        share|improve this answer














                                                                                                                                                                                                        Those notices are because you don't have the used variable defined and my_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:



                                                                                                                                                                                                        $my_variable_name = "Variable name"; // defining variable
                                                                                                                                                                                                        echo "My variable value is: " . $my_variable_name;

                                                                                                                                                                                                        if(isset($my_array["my_index"])){
                                                                                                                                                                                                        echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
                                                                                                                                                                                                        }


                                                                                                                                                                                                        Another way to get this out:



                                                                                                                                                                                                        ini_set("error_reporting", false)






                                                                                                                                                                                                        share|improve this answer














                                                                                                                                                                                                        share|improve this answer



                                                                                                                                                                                                        share|improve this answer








                                                                                                                                                                                                        answered Jan 25 at 13:09


























                                                                                                                                                                                                        community wiki





                                                                                                                                                                                                        Andrei Todorut























                                                                                                                                                                                                            up vote
                                                                                                                                                                                                            -1
                                                                                                                                                                                                            down vote













                                                                                                                                                                                                            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!.



                                                                                                                                                                                                            //If you only want to check variable has value and value has true and false value.
                                                                                                                                                                                                            //But variable must be defined first.

                                                                                                                                                                                                            if($my_variable_name){

                                                                                                                                                                                                            }

                                                                                                                                                                                                            //If you want to check variable is define or undefine
                                                                                                                                                                                                            //Isset() does not check that variable has true or false value
                                                                                                                                                                                                            //But it check null value of variable
                                                                                                                                                                                                            if(isset($my_variable_name)){

                                                                                                                                                                                                            }


                                                                                                                                                                                                            Simple Explanation



                                                                                                                                                                                                            //It will work with :- true,false,NULL
                                                                                                                                                                                                            $defineVarialbe = false;
                                                                                                                                                                                                            if($defineVarialbe){
                                                                                                                                                                                                            echo "true";
                                                                                                                                                                                                            }else{
                                                                                                                                                                                                            echo "false";
                                                                                                                                                                                                            }

                                                                                                                                                                                                            //It will check variable is define or not and variable has null value.
                                                                                                                                                                                                            if(isset($unDefineVarialbe)){
                                                                                                                                                                                                            echo "true";
                                                                                                                                                                                                            }else{
                                                                                                                                                                                                            echo "false";
                                                                                                                                                                                                            }





                                                                                                                                                                                                            share|improve this answer



























                                                                                                                                                                                                              up vote
                                                                                                                                                                                                              -1
                                                                                                                                                                                                              down vote













                                                                                                                                                                                                              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!.



                                                                                                                                                                                                              //If you only want to check variable has value and value has true and false value.
                                                                                                                                                                                                              //But variable must be defined first.

                                                                                                                                                                                                              if($my_variable_name){

                                                                                                                                                                                                              }

                                                                                                                                                                                                              //If you want to check variable is define or undefine
                                                                                                                                                                                                              //Isset() does not check that variable has true or false value
                                                                                                                                                                                                              //But it check null value of variable
                                                                                                                                                                                                              if(isset($my_variable_name)){

                                                                                                                                                                                                              }


                                                                                                                                                                                                              Simple Explanation



                                                                                                                                                                                                              //It will work with :- true,false,NULL
                                                                                                                                                                                                              $defineVarialbe = false;
                                                                                                                                                                                                              if($defineVarialbe){
                                                                                                                                                                                                              echo "true";
                                                                                                                                                                                                              }else{
                                                                                                                                                                                                              echo "false";
                                                                                                                                                                                                              }

                                                                                                                                                                                                              //It will check variable is define or not and variable has null value.
                                                                                                                                                                                                              if(isset($unDefineVarialbe)){
                                                                                                                                                                                                              echo "true";
                                                                                                                                                                                                              }else{
                                                                                                                                                                                                              echo "false";
                                                                                                                                                                                                              }





                                                                                                                                                                                                              share|improve this answer

























                                                                                                                                                                                                                up vote
                                                                                                                                                                                                                -1
                                                                                                                                                                                                                down vote










                                                                                                                                                                                                                up vote
                                                                                                                                                                                                                -1
                                                                                                                                                                                                                down vote









                                                                                                                                                                                                                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!.



                                                                                                                                                                                                                //If you only want to check variable has value and value has true and false value.
                                                                                                                                                                                                                //But variable must be defined first.

                                                                                                                                                                                                                if($my_variable_name){

                                                                                                                                                                                                                }

                                                                                                                                                                                                                //If you want to check variable is define or undefine
                                                                                                                                                                                                                //Isset() does not check that variable has true or false value
                                                                                                                                                                                                                //But it check null value of variable
                                                                                                                                                                                                                if(isset($my_variable_name)){

                                                                                                                                                                                                                }


                                                                                                                                                                                                                Simple Explanation



                                                                                                                                                                                                                //It will work with :- true,false,NULL
                                                                                                                                                                                                                $defineVarialbe = false;
                                                                                                                                                                                                                if($defineVarialbe){
                                                                                                                                                                                                                echo "true";
                                                                                                                                                                                                                }else{
                                                                                                                                                                                                                echo "false";
                                                                                                                                                                                                                }

                                                                                                                                                                                                                //It will check variable is define or not and variable has null value.
                                                                                                                                                                                                                if(isset($unDefineVarialbe)){
                                                                                                                                                                                                                echo "true";
                                                                                                                                                                                                                }else{
                                                                                                                                                                                                                echo "false";
                                                                                                                                                                                                                }





                                                                                                                                                                                                                share|improve this answer














                                                                                                                                                                                                                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!.



                                                                                                                                                                                                                //If you only want to check variable has value and value has true and false value.
                                                                                                                                                                                                                //But variable must be defined first.

                                                                                                                                                                                                                if($my_variable_name){

                                                                                                                                                                                                                }

                                                                                                                                                                                                                //If you want to check variable is define or undefine
                                                                                                                                                                                                                //Isset() does not check that variable has true or false value
                                                                                                                                                                                                                //But it check null value of variable
                                                                                                                                                                                                                if(isset($my_variable_name)){

                                                                                                                                                                                                                }


                                                                                                                                                                                                                Simple Explanation



                                                                                                                                                                                                                //It will work with :- true,false,NULL
                                                                                                                                                                                                                $defineVarialbe = false;
                                                                                                                                                                                                                if($defineVarialbe){
                                                                                                                                                                                                                echo "true";
                                                                                                                                                                                                                }else{
                                                                                                                                                                                                                echo "false";
                                                                                                                                                                                                                }

                                                                                                                                                                                                                //It will check variable is define or not and variable has null value.
                                                                                                                                                                                                                if(isset($unDefineVarialbe)){
                                                                                                                                                                                                                echo "true";
                                                                                                                                                                                                                }else{
                                                                                                                                                                                                                echo "false";
                                                                                                                                                                                                                }






                                                                                                                                                                                                                share|improve this answer














                                                                                                                                                                                                                share|improve this answer



                                                                                                                                                                                                                share|improve this answer








                                                                                                                                                                                                                answered May 17 at 2:43


























                                                                                                                                                                                                                community wiki





                                                                                                                                                                                                                Manish Goswami


















                                                                                                                                                                                                                    protected by Madara Uchiha Dec 9 '12 at 12:00



                                                                                                                                                                                                                    Thank you for your interest in this question.
                                                                                                                                                                                                                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                                                                                                                    Would you like to answer one of these unanswered questions instead?



                                                                                                                                                                                                                    Popular posts from this blog

                                                                                                                                                                                                                    404 Error Contact Form 7 ajax form submitting

                                                                                                                                                                                                                    How to know if a Active Directory user can login interactively

                                                                                                                                                                                                                    Refactoring coordinates for Minecraft Pi buildings written in Python