简化PHP中很长的if语句

时间:2018-11-21 06:49:20

标签: php if-statement

$gateway_site_id = $_POST['gateway_site_id'];
$site_location = $_POST['site_location'];
$city = $_POST['city'];
$contact = $_POST['gateway_site_id'];
$date_installed = $_POST['date_installed'];
$care_of = $_POST['care_of']; 
$notes = $_POST['notes'];
$gateway_username = $_POST['gateway_username'];



if(empty($gateway_username)){
    $gateway_username="N/A";
}if(empty($notes)){
    $notes="N/A";
}if(empty($care_of)){
    $care_of="N/A";
}if(empty($date_installed)){
    $date_installed="N/A";
}if(empty($city)){
    $city="N/A";
}if(empty($site_location)){
    $site_location="N/A";
}if(empty($gateway_site_id)){
    $gateway_site_id="N/A";
}

提交表单时,我只想使用N/A设置空字段。 我的代码有效,但是我认为它太长了,有没有办法简化它?

4 个答案:

答案 0 :(得分:3)

ternary operator检查空度,并这样写:

var responseJSON;
var maxTime = new Date(pm.globals.get("$requestMaxTime"));
try { 
    responseJSON = JSON.parse(responseBody); 
    if(responseJSON.Code !== pm.globals.get("testCODE")) {
        if(maxTime > new Date()) {
           postman.setNextRequest("Delay");
        }
        else {
            tests["code is saved"] = responseJSON.Code === pm.globals.get("testCODE");
        }
    }
    else {
        tests["code is saved"] = responseJSON.Code === pm.globals.get("testCODE");
    }
}
catch (e) { }

答案 1 :(得分:3)

类似这样的东西:

$required = ['gateway_site_id', 'site_location', 'city', 'gateway_site_id', 'date_installed', 'care_of', 'notes','gateway_username'];
foreach ($required as $req) 
        ${$req} = isset($_POST[$req]) ?  $_POST[$req] : 'N\A';

答案 2 :(得分:1)

如果您使用的是PHP 7,则可以使用合并运算符检查POST数组中的空值,例如:

$gateway_site_id    = $_POST['gateway_site_id'] ?? 'N/A';
$site_location      = $_POST['site_location']  ?? 'N/A';
$city               = $_POST['city'] ?? 'N/A';
$contact            = $_POST['gateway_site_id'] ?? 'N/A';
$date_installed     = $_POST['date_installed'] ?? 'N/A';
$care_of            = $_POST['care_of'] ?? 'N/A';
$notes              = $_POST['notes'] ?? 'N/A';
$gateway_username   = $_POST['gateway_username'] ?? 'N/A';

答案 3 :(得分:1)

尝试一下:

$gateway_site_id = empty($_POST['gateway_site_id']) ? $_POST['gateway_site_id'] : 'N/A';
$site_location = empty($_POST['site_location']) ? $_POST['site_location'] : 'N/A'; 
$city = empty($_POST['city']) ? $_POST['city'] : 'N/A'; 
$contact = empty($_POST['gateway_site_id']) ? $_POST['gateway_site_id'] : 'N/A';
$date_installed = empty($_POST['date_installed']) ? $_POST['date_installed'] : 'N/A';
$care_of = empty($_POST['care_of']) ? $_POST['care_of'] : 'N/A'; 
$notes = empty($_POST['notes']) ? $_POST['notes'] : 'N/A'; 
$gateway_username = empty($_POST['gateway_username']) ? $_POST['gateway_username'] : 'N/A';