我正在运行一个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"];

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

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

我该如何修复它们?


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


当前回答

HTML表单提交后变量不存在的一个常见原因是表单元素没有包含在<form>标记中:

示例:<表单>中不包含的元素

<form action="example.php" method="post">
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

<select name="choice">
    <option value="choice1">choice 1</option>
    <option value="choice2">choice 2</option>
    <option value="choice3">choice 3</option>
    <option value="choice4">choice 4</option>
</select>

示例:元素现在包含在<表单>中

<form action="example.php" method="post">
    <select name="choice">
        <option value="choice1">choice 1</option>
        <option value="choice2">choice 2</option>
        <option value="choice3">choice 3</option>
        <option value="choice4">choice 4</option>
    </select>
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

其他回答

保持简单:

<?php
    error_reporting(E_ALL); // Making sure all notices are on

    function idxVal(&$var, $default = null) {
        return empty($var) ? $var = $default : $var;
    }

    echo idxVal($arr['test']);         // Returns null without any notice
    echo idxVal($arr['hey ho'], 'yo'); // Returns yo and assigns it to the array index. Nice
?>

这意味着您正在测试、求值或打印一个尚未赋值的变量。这意味着你要么有一个拼写错误,要么你需要检查变量是否被初始化为其他东西。检查您的逻辑路径,它可能设置在一个路径,但不是在另一个路径。

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

$user_location = null;

在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";
}

关于这部分问题:

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

没有明确的答案,但这里有一些可能的解释,为什么设置可以“突然”改变:

您已经将PHP升级到一个新的版本,该版本可以为error_reporting、display_errors或其他相关设置设置其他默认值。 您已经删除或引入了一些在运行时使用ini_set()或error_reporting()设置相关设置的代码(可能是在依赖项中)(在代码中搜索这些代码) 你改变了web服务器配置(假设这里是apache): .htaccess文件和vhost配置也可以操作php设置。 通常通知不会被显示/报告(参见PHP手册) 因此,在设置服务器时,php.ini文件可能因为某些原因(文件权限??)而无法加载,而您使用的是默认设置。稍后,“错误”已经解决(意外),现在它可以加载正确的php.ini文件与error_reporting设置显示通知。