php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

标签 php arrays variables warnings undefined-index

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

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

Warning: Undefined array key "my_index" in C:\wamp\www\mypath\index.php on line 11


第 10 和 11 行如下所示:
echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
这些错误信息的含义是什么?
为什么他们会突然出现?我多年来一直使用这个脚本,从来没有遇到过任何问题。
我该如何修复它们?

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:

最佳答案

注意/警告: undefined variable
来自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.


来自 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.


这意味着您只能使用 empty()确定是否设置了变量,此外它还根据以下内容检查变量,0 , 0.0 , "" , "0" , null , false[] .
例子:
$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";
});
3v4l.org online PHP editor 中测试上述代码段
尽管 PHP 不需要变量声明,但它确实推荐它,以避免一些安全漏洞或错误,即人们会忘记为稍后将在脚本中使用的变量赋值。 PHP 在未声明变量的情况下所做的是发出一个非常低级别的错误,E_NOTICE ,默认情况下甚至不报告,但手册 advises to allow在开发过程中。
处理问题的方法:
  • 推荐:声明您的变量,例如当您尝试将字符串附加到 undefined variable 时。或使用 isset() / !empty() 在引用它们之前检查它们是否已声明,如:
    //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'] : '';
    

  • 从 PHP 7.0 开始,这变得更加简洁,现在您可以使用 null coalesce operator :
        // Null coalesce operator - No need to explicitly initialize the variable.
        $value = $_POST['value'] ?? '';
    
  • 设置 custom error handler对于 E_NOTICE 并将消息从标准输出重定向(可能到日志文件):
    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
    
  • 从报告中禁用 E_NOTICE。一种快速排除 E_NOTICE 的方法是:
    error_reporting( error_reporting() & ~E_NOTICE )
    
  • 使用 @ operator 抑制错误.

  • 注:强烈建议只实现第 1 点。
    注意: undefined index / undefined offset /警告:未定义的数组键
    当您(或 PHP)尝试访问数组的未定义索引时,会出现此通知/警告。
    处理问题的方法:
  • 在访问它之前检查索引是否存在。为此,您可以使用 isset() 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'] : '';
    
  • 语言结构 list() 当它试图访问一个不存在的数组索引时可能会产生这个:
    list($a, $b) = array(0 => 'a');
    //or
    list($one, $two) = explode(',', 'test string');
    

  • 两个变量用于访问两个数组元素,但是只有一个数组元素,索引 0 ,所以这将产生:

    Notice: Undefined offset: 1


    # $_POST/$_GET/$_SESSION多变的
    使用 $_POST 时,上面的通知经常出现。 , $_GET$_SESSION .对于 $_POST$_GET您只需要在使用它们之前检查索引是否存在。对于 $_SESSION您必须确保 session 以 session_start() 开始并且该索引也存在。
    另请注意,所有 3 个变量都是 superglobals并且是大写的。
    有关的:
  • Notice: Undefined variable
  • Notice: Undefined Index
  • 关于php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50585404/

    相关文章:

    php - IE9L自动将文档模式更改为IE7

    php - 一个我没有得到的错误,MYSQL PDO PHP

    javascript - 操作对象数组时 For 循环未按预期工作

    javascript - 安全地将 JS 变量传递给 PHP

    php - 我可以提取函数返回值吗?

    Python - 使用列表创建新变量

    PHP CURL SSL 连接到 XML 网关

    javascript - 我的脚本无法在 WordPress 静态站点中运行

    Java Vector 在删除时不重新排序索引,但将它们保留为空,在添加命令上重用这些空格

    arrays - Mongodb 用另一个字段更新数组