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

将不同条件的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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64