【问题标题】:Undefined index in php functionphp函数中未定义的索引
【发布时间】:2014-05-02 06:56:07
【问题描述】:

以下函数在每次表单提交成功后都会生成一条成功消息:

function CreateNotice($notice,$type='notification')
{
    $_SESSION['Message'][] =  array($type,$notice);  
}
function DisplayNotice()
{
    $str = '';
    if(count($_SESSION['Message']) > 0) ------>------>----->Line 85
    {
        for($i=0;$i<count($_SESSION['Message']);$i++)
        {
          $str.="<div class='".$_SESSION['Message'][$i][0]."Message left'>".$_SESSION['Message'][$i][1]."</div>";
        }
        unset($_SESSION['Message']);
        return $str;
    }   
}

每当在浏览器中打开页面时,它都会产生以下通知。

Notice: Undefined index: Message in /home/user/public_html/dir/subdir/test.php on line 85

有什么想法吗?

【问题讨论】:

标签: php arrays string forms function


【解决方案1】:

错误很简单:您正在从未定义的数组中访问某些内容。

例如,

$a = array(0, 1, 2, 3);
$b = $a[4]; // 4 does not exist. (0, 1, 2, 3 do)

要解决该错误,请使用 isset 进行 if 检查来验证它是否已设置。

例如,像这样。

$a = array(0, 1, 2, 3);
if (isset($a[4])) { $b = $a[4]; } // 4 doesn't exists, 
   // so we move over to the else condition 
   // (which is optional, but otherwise we get the issue that B is not defined). 
   // Once again, 0, 1, 2, 3 do exist of this array
else $b = false;

除此之外,我建议您查看用于循环数组的 foreach 语法,但这与您的问题无关。

另外,因为触发了这个错误,它很可能意味着你在调用DisplayNotice之前没有调用你的函数CreateNotice

【讨论】:

    【解决方案2】:

    在脚本顶部添加这一行(如果还没有的话)

    session_start(); // Starts the session so you can make use of $_SESSION
    

    并在DisplayNotice() 中添加这些行。

    if(isset($_SESSION['Message']))    // check this condition only is session is set
    {
        if(count($_SESSION['Message']) > 0) 
        {
        ......................
        }
    }
    

    【讨论】:

    • @Zarthus & Jenz ,似乎如果打开错误报告,所有未定义的变量都需要使用isset 函数进行检查,以避免未定义的索引或变量。除非关闭错误报告,否则没有其他方法可以避免这些通知。
    • @SilentPond,无论如何都会触发错误,error_reporting 只会为您的视图显示错误。
    • @Zarthus ,我明白这一点,但它可以帮助您识别由于编程语言语法不正确而真正存在的代码冲突。例如,如果我说你,"Me and you go there" 你会理解我,但实际上在语法上它是不正确的。仅此而已。
    • @SilentPond 这并没有减少错误。您应该修复代码中的错误,我们可能会遇到令人讨厌的副作用。确实,您的错误是一个通知。但这仍然是一个最初不应该发生的错误。我真的建议您解决出现的任何错误。即使最终用户无论如何都看不到它,也不是不修复这么简单的东西的借口。 -- 编码是比语法更精确的任务。因此,副作用也更加显着。示例:$_POST['password'] 未在登录时设置,但您的脚本无论如何都会记录用户
    【解决方案3】:

    在函数 DisplayNotice(){...} 的 if 条件中使用 **isset**

    if(count(isset($_SESSION['Message'])) > 0)
    

    【讨论】:

    • 虽然你的代码在我看来是合乎逻辑的,但它并没有消除未定义的索引。
    【解决方案4】:

    在页面顶部使用此代码

    error_reporting(0);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-03
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 2011-08-15
      • 2013-01-26
      • 1970-01-01
      相关资源
      最近更新 更多