有什么办法可以缩短这个if语句?的PHP

时间:2019-02-17 01:42:16

标签: php if-statement

我正在尝试使我的代码美观大方。有什么办法可以使if语句更短?

if(strlen($cname) > 100) {

} elseif(strlen($cowner) > 100) {

} elseif(strlen($cemail) > 200) {

} elseif(strlen($cpassword) > 100) {

}

我无法执行此操作,因为我想为每个if语句打印出一条特定的消息:

if(strlen($cname) > 100 || strlen($cowner) > 100 || strlen($cemail) > 200 || strlen($cpassword) > 100) {
  // I want to print out a message like email is too long not just one of these strings is too long
}

3 个答案:

答案 0 :(得分:1)

坦率地说,我认为您已经为尝试做的事情找到了最优雅的解决方案。

答案 1 :(得分:1)

您可以使用循环来减少行数。即使您要检查10个以上的字段,这也是一种优化的解决方案:

声明一个字段数组并循环遍历

$fields = array("cname" => 100, "cowner" => 100, "cemail" => 200, "cpassword" => 100); // key as field name and value as maximum limit - new values can be added here.

foreach($fields as $field => $length) {
   if(strlen(${$field}) > $length) {
       die("$field field can only contain $length characters"); 
   }
}

编辑:您还可以将所有错误保留在一个数组中,然后将所有错误打印在页面上。

$errors = array();
foreach($fields as $field => $length) {
   if(strlen(${$field}) > $length) {
        $errors[] = "$field field can only contain $length characters"; 
   }
}
print_r($errors);

答案 2 :(得分:0)

您已经在使用优化的代码。但是您可以对其进行更多优化,以显示错误消息。如下所示:

$invalidFieldName = '';
$invalidFieldLength = 100;
if (strlen($cname) > 100) {
    $invalidFieldName = 'CNAME';
} elseif (strlen($cowner) > 100) {
    $invalidFieldName = 'COWNER';
} elseif (strlen($cemail) > 200) {
    $invalidFieldName = 'CEMAIL';
    $invalidFieldLength = 200;   
} elseif (strlen($cpassword) > 100) {
    $invalidFieldName = 'CPASSWORD';
}

if ($invalidFieldName != '') {    
    echo $invalidFieldName." should be greater than ".$invalidFieldLength;
}

我不确定它是否会帮助您,但我希望它会帮助您。