doushitang4276 2011-02-22 18:08
浏览 44
已采纳

PHP Switch语句:这是正确的吗?

I've taken a look at the documentation for switch on php.net and as best as I can tell it checks a equality comparison between the variable in the switch and the case. However, the following code seems to work properly for all possible values (int, null, array, other):

$x = array('one','two');

switch ($x) {
   case null:
      echo "is null!";
      break;
   case is_int($x):
       echo "is int";
       break;
   case is_array($x):
      echo "is array!";
      break;
   default:
      echo "something else!";
      break;
}

From what I read, it should be comparing is_int($a) [true] to $x [an array, which evaluates to true] and giving an incorrect result.

My question is ... why is this actually working?

EDIT: sorry I had not copied it quite correctly as I'd been messing about with it. Its now in its working form

  • 写回答

3条回答 默认 最新

  • dongzhi2332 2011-02-22 19:06
    关注

    is_int($x) does not evaluate to true if x is an array. This works because array('one', 'two') is considered true, and is_array() will evaluate to true. This means it does not match null or is_int($x) (the latter comes out to false). If it's an int, then the opposite is true and is_array($x) becomes false. If $x is null, it evaluates to false, as does null in the switch. The null case will be executed for any circumstance where $x is false (try it with false, array(), 0, and others).

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度