dp610807 2012-08-29 14:15
浏览 29
已采纳

在php中切换条件案例

I use javascript to send cases to and ajax function. The cases are taken from the link id. For example, if user clicked this link: <a id="answer-yes-123">click this</a> The javascript will split the id to 3 part, and send the middle part "yes" to ajax as a case. For most cases, when ajax receives the case, if yes do this if no do that.

switch ($case) {
    case 'yes' :
        $assignment->add();
        break;
    case 'no' :
        $assignment->remove();
        break;

There's one exception-- a numerical case. If the middle part of the link is a number, I don't know how to make the switching statement. There are potentially unlimited different numbers, I can't make each of them a case, How to make a condition like if(is_int($case)) to work as a case?

  • 写回答

4条回答 默认 最新

  • dsw8292301 2012-08-29 14:18
    关注

    In the switch default: case, you can test is_int():

    switch ($case) {
        case 'yes' :
            $assignment->add();
            break;
        case 'no' :
            $assignment->remove();
            break;
        default:
            // Determine the numeric value however you need to 
            // is_int(), is_numeric(), preg_match(), whatever...
            if (is_int($case)) {
               // numeric stuff
            }
    }
    

    This is a little strange logically, because default: is typically used for the do this if nothing else is met condition. In your case though, if you don't need to further divide the numeric case much it works. Just be sure to comment it clearly in your code so you remember why you did it when you look back on it in six months.

    Update after comments:

    Since you already used the default:, I believe you can actually use an expression inside a case. This warrants even clearer commenting since it is not a common practice and goes kind of against the purpose of a switch:

    switch ($case) {
        case 'yes' :
            $assignment->add();
            break;
        case 'no' :
            $assignment->remove();
            break;
        // This actually works, but is highly weird. 
        // One of those things I can't believe PHP allows.
        // is_int(), is_numeric(), preg_match(), whatever... 
        case is_int($case):
            // Numeric stuff
            break;
        default:
            // default stuff
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line