我正在运行一个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)

其他回答

快速修复方法是在代码顶部将变量赋值为null:

$user_location = null;

我一直使用自己的有用函数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;
}

这是因为变量'$user_location'没有被定义。如果你在里面使用任何If循环,你声明了'$user_location'变量,那么你也必须有一个else循环并定义相同的。例如:

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

上面的代码将创建一个错误,因为if循环不满足,并且在else循环中没有定义“$user_location”。PHP仍然被要求回显变量。所以要修改代码,你必须做到以下几点:

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

用非常简单的语言来说:

错误在于你使用了一个变量$user_location,这个变量不是你之前定义的,它没有任何值。所以我建议你在使用这个变量之前先声明它。例如:$user_location = ";或$user_location = 'Los Angles';

这是您可能遇到的一个非常常见的错误。所以别担心;只需声明变量并享受编码。

如果你要向API发送数据,只需使用isset():

if(isset($_POST['param'])){
    $param = $_POST['param'];
} else {
    # Do something else
}

如果是由于会话导致的错误,请确保已正确启动会话。