dongpengqin3898 2012-06-27 01:59
浏览 27
已采纳

php - 交换机总是比很多其他的更好吗?

I am not so familiar with switch in php, but I heard if your code has a lot of elseif, it's better to use switch instead. I tried to change the code below into switch, but since I am checking two or three values at each elseif, it seems using elseif instead of switch is more logical to me (maybe I'm wrong).

So my question is, what do you suggest for the code below? Elseif or switch?

And if I want to change the code into switch, could you give me some hint?

Thank you so much in advance!

(By the way, block_check and report_check are checkboxes, and reported_msg is text)

public function block_user(){
    if(isset($_POST['submitted'])){

        $block_check = $_POST['block_check'];
        $report_check = $_POST['report_check'];     
        $reported_msg = $_POST['reported_msg']);

        if((!($block_check)) && (!($report_check))){
            echo "dont send, both not checked";

        }elseif(($report_check) && ($reported_msg == '')){
            echo "dont send, msg box is empty";

        }elseif((!($report_check)) && ($reported_msg != '')){
            echo "dont send, report_check is not checked";

        }elseif(($block_check) && (!($report_check)) && ($reported_msg == '')){
            echo "just process block";

        }elseif((!($block_check)) && ($report_check) && ($reported_msg != '')){
            echo "just process report";

        }elseif(($block_check) && ($report_check) && ($reported_msg != '')){
            echo "process both block and report";
        }
    }
}
  • 写回答

3条回答 默认 最新

  • dtv995719 2012-06-27 02:06
    关注

    Switch is really good in some situations but really bad for others. In your specific situation I would use if/elseif conditions.

    I use switch when the condition is simple and the expression is simple. If the condition has more than one variable and the expression is longer than about three lines I wouldn't use a switch.

    Here's a good example of a good switch:

    switch ( $type ) {
        case 'banana': 
            $valid = true;
            $price = 1;
            break;
         case 'apple': 
            $valid = false;
            $price = 2.52;
            break;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入