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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀