PHP组合变量

时间:2016-06-13 09:26:23

标签: php variables

我有以下代码:

session_start();
$error_fname = $_SESSION['error_fname'];
$error_lname = $_SESSION['error_lname'];
$error_email = $_SESSION['error_email'];
$error_email_invalid = $_SESSION['error_email_invalid'];

$error = array(
    'fname' => $error_fname,
    'lname' => $error_lname,
    'email' => $error_email,
    'email_invalid' => $error_email_invalid);

这是在页面顶部,在我的联系表单中,下面是代码:

<?php echo $error; ?>

出于某种原因,当我触发错误时,页面会刷新,并打印出以下内容:

Array

如何使它变为一个变量($ error)显示所有可能的错误?

_SESSION变量在以下文件中定义: /assets/redir/contact.php

<?php

session_start();

$_SESSION['error_fname'] = " ";
$_SESSION['error_lname'] = " ";
$_SESSION['error_email'] = " ";
$_SESSION['error_email_invalid'] = " ";

if($_POST['fname']){
if($_POST['lname']){
if($_POST['email']){
if (strstr($_POST['email'], '@') && strstr($_POST['email'], '.')) {

mail('', 'Nieuw bericht van je website!', strip_tags($_POST['message']));

header('Location: ../../index.php');

}else
$_SESSION['error_email_invalid'] = "<div class='mssg mssg_error'>Het ingevoerde e-mail adres is niet correct.</div>";header('Location: ../../index.php');
}else
$_SESSION['error_email'] = "<div class='mssg mssg_error'>Je e-mail adres is verplicht</div>";header('Location: ../../index.php');
}else
$_SESSION['error_lname'] = "<div class='mssg mssg_error'>Je achternaam is verplicht</div>";header('Location: ../../index.php');

}else
$_SESSION['error_fname'] = "<div class='mssg mssg_error'>Je voornaam is verplicht</div>";header('Location: ../../index.php');

?>    

使用var_dump($error);时,我会收到以下信息:

Var Dump

提前致谢!

1 个答案:

答案 0 :(得分:0)

$error是数组,因此您需要按此迭代并分别显示每个元素:

foreach ($error as $er) {
    if (!empty($er)) {
       echo $er;
       break; //to leave for first error
    }
}