All In One Script



PHP,HTLM,CSS,Jquery,AJAX,Javascript and etc doubts and sample codes

  • Home
  • Javascript
  • PHP
  • CSS
  • SQL/MYSQL

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

by Blogger 3:54:00 AM Arrays PHP Variables Warnings

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

I am running a PHP script, and keep getting errors like:
         Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10
Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11
Line 10 and 11 looks like this:
echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
What do these errors mean?
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
What do I need to do to 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?



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.
$o = [];
$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var,function($v){
if(!isset($v) || $v == false) {
echo "empty\n";
}
if(empty($v)) {
echo "empty\n";
}
});
Test the above snippet in PHP Sandbox
Although PHP does not require 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 he will use 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'] : '';
  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. This means they need to be written in uppercase.
Related:
  • Notice: Undefined variable
  • Notice: Undefined Index



http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef

READ MORE
SHARE :

Search This Blog

Followers

  • Popular
  • Recent
  • Comments
    How to get Real IP,ISP,Country,City and etc from Visitor using PHP
    How to efficiently iterate over each Entry in a Map?
    In Java, difference between default, public, protected, and private
    How to check if PHP array is associative or sequential?
    Length of a JavaScript object
    Does finally always execute in Java?
    How to return the date part only from a SQL Server datetime datatype
    What is the difference between “INNER JOIN” and “OUTER JOIN”?
    Get first key in a (possibly) associative array?
    Solved : curl_init() function not working in Ubuntu

Instagram

About

Popular Posts

  • How to get Real IP,ISP,Country,City and etc from Visitor using PHP
    How to get Real IP,ISP,Country,City and etc from Visitor using PHP Php Get Real visiter's IP and ISP and Country and City and Countr...
  • How to efficiently iterate over each Entry in a Map?
    How to efficiently iterate over each Entry in a Map? If I have an object implementing the  Map  interface in Java and I wish to iterate...
  • In Java, difference between default, public, protected, and private
    In Java, difference between default, public, protected, and private In Java , are there clear rules on when to use each of access modifi...
  • How to check if PHP array is associative or sequential?
    How to check if PHP array is associative or sequential? PHP treats all arrays as associative, so there aren't any built in function...
  • Length of a JavaScript object
    Length of a JavaScript object If I have a JavaScript object, say var myObject = new Object (); myObject [ "firstname" ] ...
  • Does finally always execute in Java?
    Does finally always execute in Java? I have a try/catch block with  return s inside it. Will the finally block be called? For example...
  • How to return the date part only from a SQL Server datetime datatype
    How to return the date part only from a SQL Server datetime datatype SELECT GETDATE () Returns:  2008-09-22 15:24:13.790 I want tha...
  • What is the difference between “INNER JOIN” and “OUTER JOIN”?
    What is the difference between “INNER JOIN” and “OUTER JOIN”? Also how do  LEFT JOIN ,  RIGHT JOIN  and  FULL JOIN  fit in? Answ...
  • Get first key in a (possibly) associative array?
    Get first key in a (possibly) associative array? What's the best way to determine the first key in a possibly associative array? My...
  • Solved : curl_init() function not working in Ubuntu
    Solved : curl_init() function not working in Ubuntu  Here solved the error  Fatal error: Call to undefined function curl_init() ...

statcounter



statcounter



Template Created By ThemeXpose & Blogger Templates