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 不需要变量声明,但它确实建议这样做,以避免一些安全漏洞或错误,这些漏洞或错误会忘记为稍后将在脚本中使用的变量赋值。 PHP 在未声明变量的情况下所做的是发出 E_WARNING 级别的错误。

此警告可帮助程序员发现拼写错误的变量名。此外,未初始化的变量还有其他可能的问题。因为它是stated在 PHP 手册中,

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.

意味着在主文件中未初始化,这个变量可能被包含文件中的变量重写,这可能导致不可预知的结果。为避免这种情况,最好对 php 文件中的所有变量进行初始化

处理问题的方法:

  1. 推荐:声明您的变量,例如,当您尝试将字符串附加到 undefined variable 时。或者使用 isset()在引用它们之前检查它们是否被声明,如:

     //Initializing a variable
     $value = ""; //Initialization value; 0 for int, [] for array, etc.
     echo $value; // no error
    
  2. 使用空合并运算符抑制错误。

     // Null coalescing operator
     echo $value ?? '';
    

    对于古老的 PHP 版本 (< 7.0) 可以使用带有三元的 isset()

     echo isset($value) ? $value : '';
    

    请注意,它本质上仍然是一种错误抑制,尽管只是针对一个特定的错误。因此,它可能会阻止 PHP 通过标记单元化变量来帮助您。

  3. @ operator 抑制错误.由于历史原因离开这里,但说真的,这不应该发生。

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

注意: undefined index / undefined offset /警告:未定义的数组键

当您(或 PHP)尝试访问数组的未定义索引时,会出现此通知/警告。

处理问题的方法几乎相同:

  1. 推荐:声明数组元素:

     //Initializing a variable
     $array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
     echo $array['value']; // no error
    
  2. 使用空合并运算符抑制错误":

     echo $_POST['value'] ?? '';
    

    对于数组,此运算符更合理,因为它可以与您无法控制的外部变量一起使用。因此,请考虑仅将其用于外部变量,例如 $_POST/$_GET/$_SESSION 或 JSON 输入。虽然最好先预定义/初始化所有内部数组。

    更好的是,验证所有输入,将其分配给局部变量,并在代码中一直使用它们。因此,您要访问的每个变量都是有意存在的。

相关:

关于php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44111809/

相关文章:

php - 如何创建对特定列的搜索?

PHP 子类不能实现相同的接口(interface)父类实现

javascript - 模态窗口未关闭问题

javascript - 从 JSON 对象 KEYS 创建字符串 - Vanilla JavaScript 或 lodash

variables - 如何在 Lua 中声明一个变量而不将其初始化为 nil?

php - 模态弹出窗口中的文本框未获取由更新单击触发的国家/地区值?

PHP/MYSQL更新多个表无法更新数据: Query was empty

java - 这个 : [Ljava. lang.Object; 是什么?

c++ - 在cpp/c++中使用字符串值数据声明变量名

JavaScript 没有函数的变量提升