[英]Undefined index in php function
每次成功提交表单后,以下函数都会生成一条成功消息:
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
任何想法?
错误很简单:您正在从未定义的数组访问某些内容。
例如,
$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
将此行添加到脚本顶部(如果尚不存在)
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)
{
......................
}
}
在函数DisplayNotice()中的if条件中使用**isset**
{...}
if(count(isset($_SESSION['Message'])) > 0)
在页面顶部使用此代码
error_reporting(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.