php - 使用PHP的“Notice: Undefined variable”,“Notice: Undefined index”和“Notice: Undefined offset”

标签 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


第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()来确定是否设置了变量,此外,它还会根据以下内容检查变量:00.0"""0"nullfalse[]

例:
$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不需要变量声明,但它确实推荐这样做,以避免某些安全漏洞或bug,因为这些漏洞或bug可能会忘记为变量提供值,该变量将在脚本的后面使用。 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'] ?? '';
    
  • 为E_NOTICE设置custom error handler并将消息重定向到标准输出之外(也许重定向到日志文件):
    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
    
  • 禁用E_NOTICE报告。仅排除E_NOTICE的快速方法是:
    error_reporting( error_reporting() & ~E_NOTICE )
    
  • @ operator抑制错误。

  • 注意:强烈建议仅实现第1点。

    注意:未定义索引/未定义偏移

    当您(或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');
    

  • 两个变量用于访问两个数组元素,但是只有一个数组元素index 0,因此将生成:

    Notice: Undefined offset: 1


    $_POST/$_GET/$_SESSION变量

    当使用$_POST$_GET$_SESSION时,上面的提示经常出现。对于$_POST$_GET,您只需要在使用索引之前检查索引是否存在。对于$_SESSION,您必须确保以 session_start() 开始 session ,并且索引也存在。

    另请注意,所有3个变量均为superglobals且均为大写。

    有关:
  • Notice: Undefined variable
  • Notice: Undefined Index
  • 关于php - 使用PHP的“Notice: Undefined variable”,“Notice: Undefined index”和“Notice: Undefined offset”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227390/

    相关文章:

    arrays - 将数组初始化为空白自定义类型 OCAML

    r - R 中变量的上标

    javascript - Node.js 和 Multer - 在回调函数 (req,res) 中处理上传文件的目的地

    php - 如何从 php-web 页 centos 服务器在后台运行 exec() 命令

    java - 二维数组 int 的 ArrayList

    javascript - 填充同一页面上的第二个下拉列表

    c - 从 csv 文件读入二维数组并使用 c 对数组进行排序

    objective-c - 这两种语法类型有什么区别? ( Objective-C )

    php - Django 、Python : Is there a simple way to convert PHP-style bracketed POST keys to multidimensional dict?

    php - if mysql查询中的参数