duansao6776 2012-07-09 00:44
浏览 64
已采纳

是否可以使用带表达式的switch语句作为案例?

Using if and elseif, it is possible to easily perform the comparison below, but for learning purposes I am analyzing if it is possible to have the same functionality using switch.

If $x receives a positive or negative value, I get the right output, but if $x receives 0 (zero), I get the output 'Lower', but the right output should be 'Equal'.

Here is the code:

$x = 0;

switch($x)
{
    case ($x < 0):
        echo 'Lower';
        break;

    case ($x == 0):
        echo 'Equal';
        break;

    case ($x > 0):
        echo 'Bigger';
        break;
    default:
        echo 'Not found';
}

Is it possible to use a switch statement with expressions as cases?

  • 写回答

3条回答 默认 最新

  • doupai5450 2012-07-09 00:57
    关注

    You are effectively not matching numbers any more, but matching the boolean outcome.

    Any positive or negative number casts to boolean true and only 0 casts to false, so basically for a positive or negative number you are comparing true to ($x < 0) or ($x > 0) and that gives the outcome you expect.

    However, 0 casts to false and (0 == 0) is true so you will never have a match there. And as 0 < 0 is also false, your first statement in the switch is matched.

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效