如何以更好的方式检查变量 php


How can I check variable php in a better way?

if (isset($_POST['register'])) {
    $email = $_POST['email'];
    $username = $_POST['username'];
    $pass = $_POST['password'];
    $rep_pass = $_POST['rep-password'];
    $firstname = $_POST['firstname'];
    $surname = $_POST['surename'];
    $phonenr = $_POST['phone-nr'];
    $place = $_POST['place'];    
}
if ($email != "" && $username != "" && $pass != "" && $rep_pass != "" &&  $firstname != "" && $surname != "" && $phonenr != "" && $place != "") { 
}

有没有更短的方法可以做与我在第二个if语句条件下所做的相同的事情?

$required = ['email', 'username', 'password', ...];
foreach($required as $field)
  if(empty($_POST[$field]))
    throw new EpicFailureException("Mandatory field '$field' is empty");

您可以使用预设的接受的 postvars 东西。您可以在验证等期间添加自定义错误消息,我的代码会自动实例化您的变量。唯一的问题是我不考虑破折号,但您可以考虑从表单名称中删除它们。

 $accepted = array('register','email','username','password','rep-password','firstname','surename','phone-nr','place');
$_POST = array('register'=>'blah','email'=>'blah','username'=>'blah','password'=>'blah','rep-password'=>'blah','firstname'=>'blah','surename'=>'blah','phone-nr'=>'blah','place'=>'blah');
$proper = true;
$erroron = "";
foreach($accepted as $val) {
    if(isset($_POST[$val])) {
        trim($_POST[$val]);
        if(!empty($_POST[$val])) {
            $$val = $_POST[$val];
        }
        else {
            $proper=false;
            $erroron = "Error occured on $val which is empty";
            break;
        }
    }
    else {
        $proper = false;
        $erroron = "Error occured on $val which is not defined";
        break;
    }
}
if($proper) {
echo "email = $email, you might want to consider removing dashes from form names to auto instantiate those variables";
}
else {
    echo "Not everything was done properly. The error message is: $erroron";
}
您可以将

值放入数组中,然后使用内置函数 array_filter() 。如果您不提供回调函数来array_filter()它只会删除数组的 false 或空值。然后计算修改前后的值,如果它们是!=缺少一个值。

if (isset($_POST['register'])) {
    $user['email'] = $_POST['email'];
    $user['username'] = $_POST['username'];
    $user['pass'] = $_POST['password'];
    $user['rep_pass'] = $_POST['rep-password'];
    $user['firstname'] = $_POST['firstname'];
    $user['surname'] = $_POST['surename'];
    $user['phonenr'] = $_POST['phone-nr'];
    $user['place'] = $_POST['place'];
}
$nbArg = count($user);
if($nbArg != count(array_filter($user))) {
echo "One Value is missing"
}