我有一种情况,即在将表格中的数据保存到会话时,我必须检查存储由表格数据上的检查所产生的错误的$ errors数组是否为空。
问题是数组是一个关联数组,当我使用'empty function'测试数组是否为空时,即使数组中的所有值都为空,它总是返回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");
}`
答案 0 :(得分:2)
最简单的方法是将错误数组定义为
// define errors array
$errors = array();
然后你的条件检查是否没有错误将完美
// check if data is correct and save to session
if(empty($errors)){
// Logic
}
您可以通过从每个条件中删除isset
来进一步优化您的代码。下面的代码行可以改进。
原始版本
if (isset($_POST["name"]) and empty($_POST["name"])) {
// Logic
}
改进版本
if (empty($_POST["name"])) {
// Logic
}
答案 1 :(得分:0)
因为您已使用其键初始化了$errors
,所以如果检查为空则返回false。相反,最好的方法是。
$errors = array();
// if error occurs then $errors["name"] = "Name error";
// Now you can check if $errors is empty or not
if(empty($errors)){
// store it to session
}
答案 2 :(得分:0)
你可以定义
$errors = array();
而不是
$errors = array(
'name' => "",
'username' => "",
'age' => "");
然后进行验证,可以查看empty($errors)
或count($errors)
答案 3 :(得分:0)
array_filter()
会删除空元素。所以你可以做点像......
if( empty( array_filter($errors))){
// save data in session
}