"Notice: Undefined Variable", "Notice: Undefined Index", "Warning: Undefined Array Key", and "Notice: Undefined Offset" Using PHP

Notice: Undefined variable, Notice: Undefined index, Warning: Undefined array key, and Notice: Undefined offset using PHP

Notice / Warning: 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, 0.0, "", "0", null, false or [].

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'] ?? '';

  1. 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)
  2. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:

    error_reporting( error_reporting() & ~E_NOTICE )
  3. Suppress the error with the @ operator.

Note: It's strongly recommended to implement just point 1.

Notice: Undefined index / Undefined offset / Warning: Undefined array key

This notice/warning 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

Undefined index with $_POST

In PHP, a variable or array element which has never been set is different from one whose value is null; attempting to access such an unset value is a runtime error.

That's what you're running into: the array $_POST does not have any element at the key "username", so the interpreter aborts your program before it ever gets to the nullity test.

Fortunately, you can test for the existence of a variable or array element without actually trying to access it; that's what the special operator isset does:

if (isset($_POST["username"]))
{
$user = $_POST["username"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}

This looks like it will blow up in exactly the same way as your code, when PHP tries to get the value of $_POST["username"] to pass as an argument to the function isset(). However, isset() is not really a function at all, but special syntax recognized before the evaluation stage, so the PHP interpreter checks for the existence of the value without actually trying to retrieve it.

It's also worth mentioning that as runtime errors go, a missing array element is considered a minor one (assigned the E_NOTICE level). If you change the error_reporting level so that notices are ignored, your original code will actually work as written, with the attempted array access returning null. But that's considered bad practice, especially for production code.

Side note: PHP does string interpolation, so the echo statements in the if block can be combined into one:

echo "$user is your username";

Getting some error like Warning: Undefined array key in my website in php

 try like this...
//php code
function validate_session()
{
//error_reporting(E_ERROR | E_PARSE);
$time_outvalue = 18000; // for session timeout
$lastActive = $_SESSION['lastActiveTime']??'0';
$userName = $_SESSION['USERNAME']??'';
$sessionId = $_SESSION['SESSION_ID']??'0';
$now = time();
$diff = $now - $lastActive;
$username = $userName;
$session_id = $sessionId;
if(($diff >= $time_outvalue && isset($lastActive)) || (($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'])) && ($_SESSION['REMOTE_ADDR'] != $_SERVER['REMOTE_ADDR']))){ // Session timeout

setcookie("PHPSESSID", "", time()-3600);
unset($lastActive);
unset($userName);
session_destroy();

}

$lastActive = time();
}

Beginner php Warning: Undefined array key

I'll assume you want to know how to get rid of this error message.

The first time you load this page you display a form and $_GET is empty (that's why it is triggering warnings). Then you submit the form and the fname and age parameters will be added to the url (because your form's method is 'get').

To resolve your issue you could wrap the two lines inside some if-statement, for example:

<?php if(isset($_GET['fname']) && isset($_GET['age'])): ?>
<br/>
Your name is <?php echo $_GET["fname"]; ?>
<br/>
Your age is <?php echo $_GET["age"]; ?>
<?php endif; ?>

Undefined index while trying to work with navigation bar

You need to check page query string is set or not then check further conditions:
so change your $p = $_GET['page']; to :

$p = isset($_GET['page'])?$_GET['page']:"";

Not able to fix PHP Notice: Undefined variable and Undefined index in code

you need to use isset() or empty() to check if the variable or array index are defined or not.

Line 318 and 393 can be changed to

if (!empty($refer_file)) {

for line 604 and 608 add something like the following before line 604:

$result['status'] = isset($result['status']) ? $result['status'] : 'default_status';
$result['message'] = isset($result['message']) ? $result['message'] : 'default_message';


Related Topics



Leave a reply



Submit