“Notice: Undefined variable”, “Notice: Undefined i

2019-08-28 21:43发布

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

Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10

Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11

Line 10 and 11 looks like this:

echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];

What is the meaning of these error messages?

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

How do I fix them?


This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.

Related Meta discussion:

28条回答
萌系小妹纸
2楼-- · 2019-08-28 22:25

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:

查看更多
不美不萌又怎样
3楼-- · 2019-08-28 22:25

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:

查看更多
孤傲高冷的网名
4楼-- · 2019-08-28 22:25

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:

查看更多
叼着烟拽天下
5楼-- · 2019-08-28 22:26

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')?>
查看更多
我想做一个坏孩纸
6楼-- · 2019-08-28 22:27

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.

查看更多
甜甜的少女心
7楼-- · 2019-08-28 22:27

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)){
查看更多
登录 后发表回答