doo58088 2011-11-16 03:48
浏览 65
已采纳

是php switch语句错误吗?

I have a problem want to know answer, Why the following code will print A not default?

$i = 0;
switch ($i) {
    case 'A':
        echo "i equals A"; //will printed it
        break;
    case 'B':
        echo "i equals B";
        break;
    case 'C':
        echo "i equals C";
        break;
    default:
       echo "i equals other";
}

Anyone can tell me why? I truely don't understand . My PHP version is 5.2.17 Theanks.

  • 写回答

5条回答 默认 最新

  • doucan8276 2011-11-16 03:49
    关注

    This comparison is happening:

    0 == 'A'
    

    What happens is that PHP casts the string to an integer. This results in the letter A becoming zero because it doesn't represent a number.

    Hence:

    0 == 0
    

    And that case meets the switch, and is therefore executed. Very counter-intuitive, but it's the way PHP's type system works, and is unfortunately technically not a bug.

    You can solve this by turning $i into a string like this:

    switch ((string) $i) {
    

    Or by just initializing it as a string if you can:

    $i = '0';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi