dousi6405 2012-11-15 20:44
浏览 498
已采纳

switch语句多个变量赋值而不重复

Let's say I have a switch statement like this:

switch ($var)
{
    case 'A':
       $a = 1;
       break;

    case 'B':
       $a = 1;
       $b = 2;
       break;

    case 'C':
       $a = 1;
       $b = 2;
       $c = 3;
       break;
}

Is there a way that I can structure that switch statement to have the repeated $a = 1 and $b = 2 appear like once?

  • 写回答

4条回答 默认 最新

  • douweng1904 2012-11-15 20:47
    关注

    Just revert your order of case statements and remove the break statements.

    switch ($var)
    {
        case 'C':
           $c = 3;
        case 'B':
           $b = 2;
        case 'A':
           $a = 1;
           break;
    }
    

    From the manual:

    It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下