duanao4503
2018-09-26 17:43
浏览 88
已采纳

将不同条件的if ... elseif链转换为case switch

Simple curiosity, is there any way to convert what this following into a switch loop?

PHP :

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = array('type' => 'error', 'value' => 'email');
}
elseif (!preg_match($regex_name, $username)) {
    $error = array('type' => 'error', 'value' => 'username');
}
elseif (!preg_match($regex_name, $firstname) && preg_match($regex_name, $lastname)) {
    $error = array('type' => 'error', 'value' => 'name');
}
elseif ($password !== $password_conf) {
    $error = array('type' => 'error', 'value' => 'password');
}
elseif (checkdate($birthday_d, $birthday_m, $birthday_y) == false) {
    $error = array('type' => 'error', 'value' => 'date');
}
else {
    $error = array('type' => 'success');
}

Thanks.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsuoedtom207012191 2018-09-26 20:00
    已采纳

    Just for completeness an example of what a transformation to a switch would look like:

    switch(true) {
        case (!filter_var($email, FILTER_VALIDATE_EMAIL)):
              $error = array('type' => 'error', 'value' => 'email');
              break;
        case (!preg_match($regex_name, $username)):
              $error = array('type' => 'error', 'value' => 'username');
              break;
        //...   
    }
    

    In the end this is just a complicated way to say if this is true.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题