我正在运行一个PHP脚本,并继续收到错误,如:

注意:未定义变量my_variable_name在C:\wamp\www\mypath\index.php第10行 注意:第11行未定义索引:my_index C:\wamp\www\mypath\index.php 警告:在C:\wamp\www\mypath\index.php第11行未定义数组键“my_index”

第10和11行是这样的:

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

这些错误消息的含义是什么?

为什么他们会突然出现?我曾经使用这个脚本多年,从来没有任何问题。

我该如何修复它们?


这是一个一般参考问题,供人们链接作为副本,而不是需要一遍又一遍地解释这个问题。我觉得这很有必要,因为现实世界中关于这个问题的答案都非常具体。 相关元讨论: 如何应对重复的问题? “参考问题”有意义吗?


当前回答

这些注意是因为您没有定义used变量,并且my_index键没有出现在$my_array变量中。

这些通知每次都会被触发,因为您的代码不正确,但可能您没有通知的报告。

解决bug:

$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 
}

另一种表达方式是:

ini_set("error_reporting", false)

其他回答

我一直使用自己的有用函数exst()自动声明变量。

您的代码将是-

$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;
}

试试这些

Q1:这个通知意味着$varname不是 的当前范围内定义 脚本。 Q2:在使用任何可疑变量之前,使用isset(), empty()条件可以很好地工作。

// 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'];
}

或者,作为一个快速而肮脏的解决方案:

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

关于会话的注意事项:

当使用会话时,session_start();必须放置在使用会话的所有文件中。 http://php.net/manual/en/features.sessions.php

使用三元运算符简单、易读、干净:

Pre PHP 7

将一个变量赋给另一个变量的值,否则赋null(或任何你需要的默认值):

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

PHP 7 +。

除了使用空合并运算符外,都是一样的。不再需要调用isset(),因为它是内置的,也不需要提供要返回的变量,因为它假设返回正在检查的变量的值:

$newVariable = $thePotentialData ?? null;

这两者都将阻止OP的问题的通知,并且两者都完全等价于:

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

如果你不需要设置一个新变量,那么你可以直接使用三元操作符的返回值,例如使用echo,函数参数等:

回音:

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

功能:

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

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

上面的方法同样适用于数组,包括会话等,将检查的变量替换为:

$ _SESSION(“checkMe”)

或者取决于你需要多少层深度,例如:

美元的客户(“个人”)(“地址”)(“邮政编码”)


抑制:

可以用@屏蔽PHP通知或降低错误报告级别,但这并不能解决问题。它只是停止在错误日志中报告它。这意味着您的代码仍然试图使用一个未设置的变量,这可能意味着某些事情没有按照预期的方式工作——这取决于缺少的值有多重要。

您确实应该检查这个问题并适当地处理它,或者提供不同的消息,或者甚至只是为其他所有内容返回一个空值,以确定准确的状态。

如果您只关心通知不在错误日志中,那么可以选择忽略错误日志。

在PHP中,首先需要定义变量。之后你就可以使用它了。

我们可以以一种非常有效的方式检查变量是否定义!

// 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 if the variable is defined or undefined
// Isset() does not check that variable has a true or false value
// But it checks the null value of a variable
if(isset($my_variable_name)){

}

简单的解释

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

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

抛出未定义索引通知的另一个原因是数据库查询中遗漏了一列。

例如:

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

然后尝试访问循环中的更多列/行。

例如:

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

或者在while循环中:

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

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

}

另外需要注意的是,在*NIX操作系统和Mac OS X上,事情是区分大小写的。

参考Stack上的以下问答:

MySQL中的表名是否区分大小写? Mysql查询中区分大小写的表名 MySql -表在不同服务器中的大小写敏感问题