【发布时间】:2018-01-14 07:58:08
【问题描述】:
我有一种情况,为了将数据从表单保存到会话中,我必须检查 $errors 数组是否存储了对表单数据进行的检查生成的错误。
问题是数组是一个关联数组,当我使用“空函数”来测试数组是否为空时,即使数组中的所有值都为空,它也总是返回 flase,我该怎么做才能检查是否关联数组为空,下面是我的代码
session_start();
// define errors array
$errors = array(
'name' => "",
'username' => "",
'age' => "");
// check and sanitize form data
if (isset($_POST["name"]) and empty($_POST["name"])) {
$errors['name'] = "your name is needed";
}else{
$_POST['name'] = test_input($_POST['name']);
if(!preg_match("/^[a-zA-Zéèàêâùïüë.',_ ]+$/",$_POST['name'])) {
$errors['name'] = "only letters and white spaces accepted";
}else{
$validator++;
}
}
if (isset($_POST["username"]) and empty($_POST["username"])) {
$errors['username'] = "your username is needed";
}else{
$_POST['username'] = test_input($_POST['username']);
if(!preg_match("/^[a-zA-Zéèàêâùïüë.',_ ]+$/",$_POST['username'])) {
$errors['username'] = "only letters and white spaces accepted";
}else{
$validator++;
}
}
if (isset($_POST["age"]) and empty($_POST["age"])) {
$errors['age'] = "age is needed";
}else{
$_POST['age'] = test_input($_POST['age']);
if(!preg_match("/^[1-90]+$/",$_POST['age'])) {
$errors['age'] = "only numbers accepted";
}else{
$validator++;
}
}
// check if data is correct and save to session
if(empty($errors)){
// save data in session
$_SESSION['name'] = $_POST['name'];
$_SESSION['username'] = $_POST['username'];
$_SESSION['age'] = $_POST["age"];
}else{
session_destroy();
header("location :index.php");
}`
【问题讨论】: