数组-未定义的偏移量,即使我已经定义了它


Array - Undefined offset even if i already defined it

我有两个页面,第1页包含这样的数组:

 $error=array();
 $error[]='First value';
 $error[]='Second value';
 $error[]='Third value';

第2页是我使用数组值的地方:

include 'page1.php';
echo '<p>'.$error[0].'</p>';
echo '<p>'.$error[1].'</p>';
echo '<p>'.$error[2].'</p>';

它应该可以工作,但它一直显示错误:

Notice: Undefined offset: 0 
Notice: Undefined offset: 1
Notice: Undefined offset: 2

知道吗?

根据您更新的问题,它显示

$error=array();
if( !empty($_POST['email']) && isset($_POST['email']) ){
      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error[] = 'Emailul nu este valid!'; 
      }else{ $email=$_POST['email']; }
 }else{ $error[]='Utilizatorul este obligatoriu!'; }

在包含的文件中,您应该通过执行var_dumps 来检查条件逻辑

var_dump($_POST)并查找"电子邮件"索引。

也许"电子邮件"存在的条件没有得到满足!

已编辑,显示以下原件。。。

通常,您会发现使用foreach循环不太容易出错。

foreach($error as $err) {
  echo '<p>'.$err.'</p>';
}

此外,您可以尝试使用而不是include file.php,使用require('file.php')甚至require_once('file.php')

您的代码中有一个语法错误,这就是您出现该错误的原因。我试着成为你的调试器,试试看。刚刚修改了您的代码。

echo '<td><input type=text name=email placeholder=Email value=</td>';
if(!empty($_POST['email']))
    echo $_POST['email'];
echo '<td>'.$error[1].$error[2].'</td>';  //Problem is here 
$error=array();
if( !empty($_POST['email']) && isset($_POST['email']) ){
      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error[] = 'Emailul nu este valid!'; 
      }else{ $email=$_POST['email']; }
 }else{ $error[]='Utilizatorul este obligatoriu!'; }

//这里的问题是,尚未分配索引3上的$error[3]元素。

根据你所做的,你可能应该做一个多维关联数组,这样错误就属于这样的类别:

$error['email'][] = 'error text';
$error['rparola'][] = 'error text';

使您的$error报告有条件:

if(isset($error['email'])) { do stuff }