我该如何缩短php代码?

时间:2017-11-10 10:24:01

标签: php

如果没有这么多的if循环,我如何修改我的代码才能“更智能”工作?我附上我迄今为止所尝试的内容。

$error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["fname"])) {
      $error1 = "fill in fname";
    }  
    if (empty($_POST["lname"])) {
      $error2 = "fill in lname";
    } 
    if (empty($_POST["street"])) {
      $error3 = "fill in street";
    }  
    if (empty($_POST["city"])) {
      $error4 = "fill in city";
    } 
    if (empty($_POST["postcode"])) {
      $error5 = "fill in postcode";
    } 
    if (empty($_POST["country"])) {
      $error6 = "fill in country";
    } 
    if (empty($_POST["email"])) {
      $error7 = "fill in email";
    } 
    if (empty($_POST["phone"])) {
      $error8 = "fill in phone";
    }
}

提前致谢!

2 个答案:

答案 0 :(得分:1)

请检查

$formfields = array('fname','lname','street','city','postcode','country','email','phone');
$errMsg = "";
 if(isset($_POST) && count($_POST)>0){
    foreach($_POST as $key => $val){
        if(in_array($key, $formfields)){
            if (empty($_POST[$key])) { $errMsg[] = "fill in ". $key; }  
        }
    }
 }

 if(count($errMsg)>0)
    echo implode("<br/>",$errMsg);

答案 1 :(得分:1)

试试这个:

$errors = array();
$inputs = array("fname", "lname", "street", "city", "postcode", "country", "email", "phone");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    foreach($_POST as $key => $arg) {
        if(in_array($key, $inputs) && empty($arg)){
            $errors[] = "fill in " . $key;
        }
    }
}